How to use seeder in laravel?
A Laravel Seeder is a feature of the Laravel PHP framework that allows you to populate your database with test or dummy data. This is particularly beneficial during the development, testing, and demo stages of your application.
All seed classes are stored in the `database/seeders` directory. By default, a `DatabaseSeeder` class is defined for you. From this class, you may use the `call` method to run other seed classes, allowing you to control the seeding order.
To generate a seeder, you can execute the `make:seeder` Artisan command. A seeder class only contains one method by default: `run`. This method is called when the `db:seed` Artisan command is executed. Within the `run` method, you may insert data into your database however you wish. You may use the query builder to manually insert data or you may use Eloquent model factories.
php artisan make:seeder UserSeeder
After running the command, A seeder file named `UserSeeder.php` will be created in `database/seeders` directory.
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
User::create([
'username' => Str::random(10),
'name' => Str::random(10),
'email' => Str::random(10).'@example.com',
'mobile' => '911234567891',
'password' => Hash::make('password'),
'status' => 1
]);
}
}
The call method is used to execute additional seed classes within the DatabaseSeeder class. It allows you to break up your database seeding into multiple files so that no single seeder class becomes too large. The call method accepts an array of seeder classes that should be executed.
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call([
UserSeeder::class
]);
}
}
php artisan db:seed
To run specific seeder use this command
php artisan db:seed –class=UserSeeder
You can also seed your database using the migrate:fresh command in combination with the -seed option. This command drops all tables, re-runs all of your migrations, and re-building your database.
php artisan migrate:fresh --seed
Tags
Related Posts
How to upload file in laravel through an API?
How to create custom command in laravel?
How to integrate ChatGPT image generation into Laravel?
How to create and integrate a ChatGPT AI bot into Laravel?
How to upload image in summernote laravel?
How to save image from a url in laravel?
How to use seeder in laravel?
How to edit env dynamically in laravel?
How to solve CORS error in laravel?
How to create a common dynamic modal in Laravel?