Here, I will explain you how to create seeder in laravel.You can easily understand a concept of laravel seeder example. you will learn laravel Create Seeder database example.
you have question what is seeder and how to create seeder in laravel? and why do we have to use seeder in laravel application.
Laravel provide a seeder for creating testing data and if you have a small project then you can create an user and also set table default data.
when you have an project that doesn’t have a register page then what you will do?so basically he can log in and access the whole admin panel.you can create one admin directly database.But i will suggest you can create an user using laravel seeder.just run command seeder in laravel.
In this tutorial, I will explain how to create seeder in laravel and what is command to create a seeder and how to run seeder command in laravel.Like make:seeder so you have follow a few step to get how it’s done.
Create Seeder Class
Laravel provide command to create seeder in laravel.so you can run following command to create DatabaseSeeder in laravel project.
How to create seeder in laravel Command
php artisan make:seeder UserSeederData
then running the above command, it will create one file UserSeederData.php on the seeder folder.All seeder file stored in the database/seeders directory.you can integrate code specific model.
Read also: How to use Soft Delete in Laravel
database/seeders/UserSeederData.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;
class UserSeederData extends Seeder
{
public function run(): void
{
User::create([
'name' => 'test',
'email' => 'your email address',
'password' => bcrypt('12345');
]);
}
}
?>
As you can show above code,simply create a new user in my users table now.how you can run this seeder manually.
There is a two way to run this seeder.I will give you both ways to run seeder in laravel.
Step 1 : Run Single Seeder
You need to run following command to run single seeder method.
php artisan db:seed --class=UserSeederData
Step 2: Run All Seeders
In this way, you have to explain your seeder in the DatabaseSeeder class file.after you have to run a single command to run all listed seeder class.
database/seeders/DatabaseSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run() : void
{
$this->call(UserSeederData->class);
}
}
Now you need to run following command for run all seeder:
php artisan db:seed
Now i hope you will understand how to seeding works and we have to use it in our laravel poject.
I hope this tutorial help you…