What is Seeder in Laravel and Why we need it?
Categories - Laravel PHP Framework Tags - Laravel   Maniruzzaman Akash   1 year ago   1043   0

What is Seeder in Laravel and Why we need it?

What is Seeder in Laravel

Seeder or called Database Seeder is a feature of Laravel Php framework, which is used to auto generate data when an initial version is instantiated. 

 

Why Use Seeder in Laravel

We use a seeder to test our laravel project quickly and efficiently. Like in a scenerio in a Laravel project, where we have to make migrate:refresh command which drops the old migrations and write new migrations in database.

So, what If our projects has 25 blog posts by which our site is visible fully. Ok, now if make that command, datbase actually clear, right? So, will we put 25 posts again in database and check if everythings right.

Or in another example would be we had two test users and check site by that's user ID, now create again that two test users in database and check project ?

Ok, so think once that how much painful would be that for you. Actually you may doing this currently right or not?

So, we'll make this process simple using the Laravel Database Seeder.  

 

How to Create Seeder in Laravel

Ok, let's start to create a seeder in Laravel.

By default Laravel comes with a Seeder pattern in database/seeder folder. To Create a Seeder in that folder, we can use Laravel Seeder Command -

php artisan make:seeder PostSeeder

After this command, A PostSeeder.php file will be generated with class name PostSeeder. Check the image below-

Laravel-Seeder-Example

Assume, We want to create 10 dummy post in PostSeeder.

 Steps to make dummu posts using Laravel Database Seeder.

Step 1:

Create a database migration for Post Model. We'll create a post model and with a migration

php artisan make:model Post -m

So, put the below migrations in  2020_07_20_133415_create_posts_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug')->index();
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

We've just created a post model with title, slug and description.

Step 2:

Now add fake 1000 posts in PostSeeder using also Laravel Faker. So, PostSeeder.php file would be,

<?php

use App\Post;
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;

class PostSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create();
        for ($i = 0; $i < 100; $i++) {
            Post::create([
                'title' => $faker->jobTitle,
                'slug' => $faker->unique()->slug(),
                'description' => $faker->text()
            ]);
        }
    }
}

So, in our run(),

  1. we've first instantiated the Faker instance.
  2. Then loop throw 100 to generate 100 posts.
  3. Inside loop, we've create Post, using Laravel create() function.
  4. We've used th title, slug, description data of the faker class data. You could also use as your purpose data here.

 

Step 3:

Add this PostSeeder class in DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(PostSeeder::class);
    }
}

 

Step 4:

Now everything is set up. Now run the db:seed artisan command.

php artisan db:seed

 

Any Problem ?

Probably there could be need to autoload seeder class and run the following commands - 

composer dump-autoload

php artisan optimize

php artisan db:seed

 

So, after this in your database there would be 100 posts stored and boom. Your site has now a full visibility and load testing also..

 

Step 5: More

You could also run a specific seeder like this,, we'll only seed the PostSeeder. 

php artisan db:seed --class=PostSeeder

 

To refresh migrations and run seeder, there is also a command like this -

php artisan migrate:fresh --seed

 

To forcely Seed of the seeder - 

php artisan db:seed --force

 

That is a basic and real life example of Laravel Database Seeder.

Official DOcumentation of Laravel about Database Seeder is here - https://laravel.com/docs/7.x/seeding#introduction

 

Previous
#5 Laravel Views
Next
Higher Order Component in React - In depth discussion about React HOC