Tutorial

How To Populate a Database with Sample Data using Laravel Seeders and Eloquent Models

Published on July 29, 2021

Developer Advocate

How To Populate a Database with Sample Data using Laravel Seeders and Eloquent Models

Laravel’s Seeders are special classes that live in the database/seeders directory in a Laravel project that allow you to programmatically insert a collection of default or sample records in the database. The demo application has a seeder class that imports links from a links.yml file in the root of the application folder.

In your code editor, open the following file:

database/seeders/LinkSeeder.php

It will contain the following code:

database/seeders/LinkSeeder.php
<?php
 
namespace Database\Seeders;
 
use App\Models\Link;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Yaml\Yaml;
 
class LinkSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //only import seeds if DB is empty.
        if (!Link::count()) {
            $this->importLinks();
        }
    }
 
    /**
     * Imports Links from the default links.yml file at the root of the app.
     * Change that file to import a set of personal basic links you want to show
     * as soon as the application is deployed.
     */
    public function importLinks()
    {
        $links_import_path = __DIR__ . '/../../links.yml';
 
        $yaml = new Yaml();
        if (is_file($links_import_path)) {
            $links = $yaml->parsefile($links_import_path);
 
            foreach ($links as $link) {
                DB::table('links')->insert([
                    'url' => $link['url'],
                    'description' => $link['description']
                ]);
            }
        }
    }
}
 

Notice that this code does not use the Link model and instead uses the query builder to insert new links in the database. This is a different way of working with database records in Laravel that doesn’t depend on Eloquent models. Even though this works well, by using Eloquent models you’ll have access to a series of helpful methods and shortcuts to make your code more concise and easier to read.

To improve this code, you’ll change the foreach loop to use Eloquent models instead of querying the database directly with the query builder. You’ll also have to create a default list of links (called $default_list in the following code) before the loop is started, so that you can reference this list in each new link created.

Replace the current content in your seeder class with the following code:

database/seeders/LinkSeeder.php
<?php
 
namespace Database\Seeders;
 
use App\Models\Link;
use App\Models\LinkList;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Yaml\Yaml;
 
class LinkSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //only import seeds if DB is empty.
        if (!Link::count()) {
            $this->importLinks();
        }
    }
 
    /**
     * Imports Links from the default links.yml file at the root of the app.
     * Change that file to import a set of personal basic links you want to show
     * as soon as the application is deployed.
     */
    public function importLinks()
    {
        $links_import_path = __DIR__ . '/../../links.yml';
 
        $yaml = new Yaml();
        if (is_file($links_import_path)) {
            $links = $yaml->parsefile($links_import_path);
 
            $default_list = new LinkList();
            $default_list->title = "Default";
            $default_list->description = "Default List";
            $default_list->slug = "default";
            $default_list->save();
 
            foreach ($links as $link) {
                $seed_link = new Link();
                $seed_link->url = $link['url'];
                $seed_link->description = $link['description'];
 
                $default_list->links()->save($seed_link);
            }
        }
    }
}
 
 

The updated code uses an object-oriented approach for setting up the properties for the LinkList and List models that are translated into table columns by Eloquent. The final line of the for loop uses the $default_list reference to the links table, which is accessed via the method links(), to save new links within that list.

Save the file when you’re done. Laravel seeders will only run when the database is empty, so as to not conflict with actual data that was inserted in the database by other means. Thus in order to run the modified seeder, you’ll need to wipe the database once again with the artisan db:wipe command…

Run the following command to wipe the development database:

  1. docker-compose exec app php artisan db:wipe
Output
Dropped all tables successfully.

Now to recreate the tables and run the updated seeders, you can use the following artisan migrate --seed command:

  1. docker-compose exec app php artisan migrate --seed

You should receive output that is similar to the following:

Output
Migration table created successfully. Migrating: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table (124.20ms) Migrating: 2014_10_12_100000_create_password_resets_table Migrated: 2014_10_12_100000_create_password_resets_table (121.75ms) Migrating: 2019_08_19_000000_create_failed_jobs_table Migrated: 2019_08_19_000000_create_failed_jobs_table (112.43ms) Migrating: 2020_11_18_165241_create_links_table Migrated: 2020_11_18_165241_create_links_table (61.04ms) Migrating: 2021_07_09_122027_create_link_lists_table Migrated: 2021_07_09_122027_create_link_lists_table (112.18ms) Seeding: Database\Seeders\LinkSeeder Seeded: Database\Seeders\LinkSeeder (84.57ms) Database seeding completed successfully.

In the next chapter of this series, you’ll learn in more detail how to query database records with Eloquent.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


Tutorial Series: A Practical Introduction to Laravel Eloquent ORM

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. In this project-based series, you’ll learn how to make database queries and how to work with relationships in Laravel Eloquent. To follow along with the examples demonstrated throughout the series, you’ll improve a demo application with new models and relationships. Visit the series introduction page for detailed instructions on how to download and set up the project.

About the authors
Default avatar

Developer Advocate

Dev/Ops passionate about open source, PHP, and Linux.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.