Laravel

How to Create or Register Multiple Database Seeders in Laravel

Laravel

How to Create or Register Multiple Database Seeders in Laravel

Database seeders in Laravel allow you to populate your database with sample or default data, making it easier to develop and test your application. Laravel's database seeding functionality is powerful and flexible, and you can create and register multiple seeders to populate different tables. In this tutorial, we'll guide you through the process of creating and registering multiple database seeders in Laravel with an example.

Step 1: Create Seeders

In your Laravel project, you can create multiple seeders using the make:seeder Artisan command. For example, to create two seeders named UsersTableSeeder and ProductsTableSeeder, run the following commands:

php artisan make:seeder UsersTableSeeder
php artisan make:seeder ProductsTableSeeder

This will generate two seeder files in the database/seeders directory.

Step 2: Define Seeder Logic

Open each seeder file (UsersTableSeeder.php and ProductsTableSeeder.php) in the database/seeders directory and define the logic for populating the respective tables. For example:

// UsersTableSeeder.php
use Illuminate\Database\Seeder;
use App\Models\User;

class UsersTableSeeder extends Seeder
{
    public function run()
    {
        User::create([
            'name' => 'John Doe',
            'email' => 'john@example.com',
            'password' => bcrypt('secret'),
        ]);

        // Add more user data as needed
    }
}
// ProductsTableSeeder.php
use Illuminate\Database\Seeder;
use App\Models\Product;

class ProductsTableSeeder extends Seeder
{
    public function run()
    {
        Product::create([
            'name' => 'Product 1',
            'price' => 19.99,
        ]);

        // Add more product data as needed
    }
}

Step 3: Register Seeders

Open the DatabaseSeeder.php file located in the database/seeders directory. This file is the main entry point for registering your seeders.

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->call([
            UsersTableSeeder::class,
            ProductsTableSeeder::class,
            // Add more seeders here
        ]);
    }
}

Step 4: Run Seeders

To run the registered seeders and populate your database, use the db:seed Artisan command:

php artisan db:seed

You can also specify specific seeders to run:

php artisan db:seed --class=UsersTableSeeder
php artisan db:seed --class=ProductsTableSeeder

Conclusion

Creating and registering multiple database seeders in Laravel allows you to easily populate different tables with sample data. This is particularly useful during development and testing phases. By following the steps in this tutorial and customizing the seeder logic to your needs, you can efficiently seed your database with the necessary data for your application.