LARAVEL

Laravel To create a database seeder


To create a database seeder in Laravel, you can follow these steps:

 

step 1. Generate a Seeder Class: 

Use the make:seeder Artisan command to generate a new seeder class. Open your terminal and run:

 php artisan make:seeder ExampleTableSeeder

Replace ExampleTableSeeder with the name of your seeder.

 

step 2. Define Seed Data: 

Open the generated seeder file (located in the database/seeders directory) and define the logic to populate your database with sample data. You can use Eloquent models or the query builder to create records.

Here's an example of what the seeder might look like:

 use Illuminate\Database\Seeder;
 use App\Models\Example;

 class ExampleTableSeeder extends Seeder
 {
     public function run()
     {
         // Populate the database with sample data
         for ($i = 0; $i < 10; $i++) {
             Example::create([
                 'name' => 'Example ' . ($i + 1),
                 'description' => 'Description for Example ' . ($i + 1),
             ]);
         }
     }
 }

Replace App\Models\Example with the appropriate namespace and model name for your application.

 

3. Call the Seeder: 

You can call your seeder class within the DatabaseSeeder class or run it directly using the db:seed Artisan command.

If you want to run only this seeder, you can specify its class name using the --class option:

 php artisan db:seed --class=ExampleTableSeeder

 


LARAVEL