Laravel Seeder. What is it? How to use?

Both Laravel Migrations and Laravel Seeder are pretty interesting features of Laravel. We discussed What Laravel Migrations are and how to use them.  Today we’re learning What is Laravel Seeder and How to use it to ease your Laravel development.

What is Laravel Seeder

“Laravel Seeder is a way of inserting set of data to the database by running a single command. “

Well, this is quite confusing right ? Inserting data means ? Well, it’s not a regular Database query that insert or update data. When you have a large set of data, for example you have all the city names of your country. You just want to insert them into your cities table. Imagine inserting hundreds of records manually. Well, that’s where Laravel Seeder can be really useful.

How to use Laravel Seeder

Now you got an idea what Laravel Seeder is. Now let’s get to know how to use them in your project.

First, Install a fresh copy of Laravel. 

Then create a table named cities. Using Laravel Migrations to create the table is the best and easiest way Use any number of columns as you wish. I’m adding id and name. Just to simplify things.

Alright, now you’ve got the table ready and just need to insert your cities into the table. For that, we need to create a Laravel Seeder. Run the following command in the terminal.

php artisan make:seeder CitiesTableSeeder

Great! Now open up Database > Seeds folder. You’ll see the seeder file you just created resides with DatabaseSeeder.php. 

Laravel Seeder

Alright! Now, let’s open up that CitiesTableSeeder.php file and some code to define our data.

Inside the CitiesTableSeeder.php file, there’s a method name run(). That’s where we write our code. Define your data just as follows.

public function run()
{
    DB::table('cities')->truncate();
    DB::table('cities')->insert([
        ['id' => 1, 'name' => 'Alabama'],
        ['id' => 2, 'name' => 'Alaska'],
        ['id' => 3, 'name' => 'Arizona'],
        ['id' => 4, 'name' => 'Arkansas'],
        ['id' => 5, 'name' => 'California'],
   ]);
}

Define records as many as you want. Once you’re done, you need to add this to the Laravel DatabaseSeeder.php. Checkout the below code.

public function run()
{
    $this->call(CitiesTableSeeder::class);
}

Great! Now only thing we need to do is just running this seed. Actually, there’s one more thing to do before running the seeder. We need to regenerate the composer’s auto loader. For that, run the following command.

composer dump-autoload

Now run the following command to run the Seed you created.

php artisan db:seed

This will run all the seeds available. Use the following command to run only a specific seed.

php artisan db:seed –class=CitiesTableSeeder

Refer to Laravel Seeder documentation for a detailed view of these commands and other stuff.

That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *