Laravel 12 Factory and Seeder Implementation

Laravel 12 has built in features of factory and seeder. Factory and seeder are mainly used for generating fake data. We may stay in confusion why factory and seeder is used in laravel actually. A Seeder is mainly used to populate the database with data. It is a class that contains instructions for inserting records into a database table. We typically use seeders to store predefined data into database tables (like default user roles, settings, or other essential records) during development or testing.


Why Use Seeders?

  1. Populate database with test data: Seeders allows  to quickly add data in tables for testing purposes.
  2. Consistent development environment: Seeders ensure that all developers working on the same project can quickly populate their database with the same data and pattern.
  3. Initialization of default data: We can use seeders to insert default or essential data (e.g., admin users or roles) that our application needs to function properly.

In this article I explain all of these related to factory as well as seeder. Also here real coding example will be given.

Here we will create a course model, it's related factory and also migration. After that we will run and populate fake data using seeder

Create Course Model

For creating course model we will use below command along with some options.

Here f refers to factory, m refers to migration and s for seeder.

php artisan make:model Course -fms


This will create a Couse model inside app/Models/Course.php


namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Course extends Model
{
    /** @use HasFactory<\Database\Factories\CourseFactory> */
    use HasFactory;
}


-fms option has already created CourseFactory and CourseSeeder .

Read also: Laravel 12 features review and installation

Read also: Laravel 11 intervention image upload

CourseFactory

//database/factories/UserFactory.php
namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Course>
 */
class CourseFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition(): array
    {
        return [
            'course_name' => $this->faker->sentence(3), // Random course name (e.g., 'PHP Programming')
            'duration' => $this->faker->randomElement(['3 months', '6 months', '1 year']), // Random duration
            'start_date' => $this->faker->date(), // Random start date
            'end_date' => $this->faker->date(), // Random end date
            'status' => $this->faker->randomElement([0, 1]), // Random status (0 or 1)
        ];
    }
}


CourseSeeder

//database/seeders/CourseSeeder.php
namespace Database\Seeders;

use App\Models\Course;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class CourseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        Course::factory()->count(10)->create(); // Creates 10 courses
    }
}


Add CourseSeeder class to DatabaseSeeder class file

//database/seeders/DatabaseSeeder.php
namespace Database\Seeders;

use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // User::factory(10)->create();
        $this->call(CourseSeeder::class);

        User::factory()->create([
            'name' => 'Test User',
            'email' => '[email protected]',
        ]);
    }
}

Read also: Laravel 11 chat app using reverb broadcasting event

Read also: Laravel remove public from url in shared hosting

Read also: Laravel export collection to xlsx file download

Now run seeder using below command. This command will run all the seeders added in DatabaseSeeder.php file

php artisan db:seed

If you want to run specific seeder then you will have to run command along with option

php artisan db:seed --class=CourseSeeder


Here is the generated data by seeder 

laravel database seeder file - programmingmindset.com

Tags: