How To Seed Data In Laravel 9

Hello Friends,
Today We see how to seed data in database in laravel 9 but before seed lets have look what is seeder. Seeder use for insert data in database without any forms and function. its very easy way to insert data in mysql database. so lets get started

Create Seeder Class:

Laravel gives command to create seeder in laravel. so you can run following command to make seeder in laravel application.

Create Seeder Command:

php artisan make:seeder AdminUserSeeder

after running the above command, it will create one file AdminUserSeeder.php on the seeders folder. All seed classes are stored in the database/seeders directory.

Read Also :  How to Clear Route Cache in Laravel

 

Then you can write code of create admin user using model in laravel.

database/seeders/AdminUserSeeder.php

<?php
  
namespace Database\Seeders;
  
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;
  
class AdminUserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::create([
            'name' => 'Rohit',
            'email' => 'rohit@gmail.com',
            'password' => bcrypt('123456'),
        ]);
    }
}

As you can see above code, I simply write creating a new user in my users table now. so you can add your code to write admin user creating. Now, how you can run this seeder manually.

Read Also :  Laravel 8 Find Nearest Location By Latitude and Longitude

 

There is a two way to run this seeder. I will give you both ways to run seeder in laravel 9.

You need to run following command to run single seeder:

php artisan db:seed --class=AdminUserSeeder