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:
<?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:
<?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:
- docker-compose exec app php artisan db:wipe
OutputDropped all tables successfully.
Now to recreate the tables and run the updated seeders, you can use the following artisan migrate --seed
command:
- docker-compose exec app php artisan migrate --seed
You should receive output that is similar to the following:
OutputMigration 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.
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.
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!
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.