Laravel seeding the database

β€” 4 minute read

permalink

Yesterday we made our first database, and another cool function of Laravel is the option to seed it.

The default installation comes with a basic database/seeders/DatabaseSeeder.

This is a collection place to run specific seeders. For our one, we will create a separate new one.

Creating the Laravel seeder permalink

Let's first generate a new seeder for our newly created books table.

php artisan make:seeder BookSeeder

This will generate the BookSeeder.php file for us. Let's change the run function to create 10 random books for us.

public function run()
{
foreach (range(1, 10) as $index) {
$year = rand(1700, 2020);
DB::table('books')->insert([
'title' => Str::random(10),
'year' => $year,
]);
}
}

To run this function, we need to make one adjustment in our main DatabaseSeeder file.

public function run()
{
$this->call([
BookSeeder::class
]);
}

And then, we can run it by executing the following command.

php artisan db:seed

This creates 10 random books, as you can see in the image below.

Laravel seeded database

Using the Laravel seeder with a Factory permalink

As you saw above, that is one way of entering our database entries. Still, we can also make use of something called Model factories. They are generally used when you need to enter large data sets.

Let's create a new factory for our Books model.

php artisan make:factory BookFactory

The Factory, however, works on Models, so let's also create an empty Book model for now.

php artisan make:model Book

Then inside the BookFactory, we can set the model to be the Book model we just created.

use App\Models\Book;

protected $model = Book::class;

And let's add some data for our definition.

public function definition()
{
return [
'title' => $this->faker->realText(50),
'year' => rand(1700, 2020),
];
}

This again will just generate some random text for our titles and pick a random year.

Next up, we need to make some changes to our BookSeeder.php file.

Book::factory()
->count(10)
->create();

This says, use the BookFactory to create 10 entries.

If we now run our seeder again, we should see another 10 random entries.

Laravel seeder with Factory

Pretty cool, right!

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter