Factory

Laravel Eloquent ORM Factory

Start new model factory

1. Create new Factory Instance

namespace Database\Factories;
 
use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Factories\Factory;
 
class UserFactory extends Factory
{
    protected $model = User::class;

    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }
}

2. Use Factory on the Model

namespace App\Models;

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

class User extends Model
{
    protected static function newFactory()
    {
        return UserFactory::new();
    }
}

Methods

Create Model from factory

It will only create the Model Instance and it WILL NOT create the data on the database.

// Create Model
$UserModel = User::factory()->make();

// Create 3 Model Collection
$UserModelCollection = User::factory()->count(3)->make();

Overwrite factory attributes

You can pass the attributes to the make() or state() method to override the attributes.

// factory make parameter
$UserModel = User::factory()->make([
    'name' => 'Custom Name',
]);


// factory state method
$UserModel = User::factory()->state([
    'name' => 'Custom Name',
])->make();

Create factory data to database

You can use the create method to insert the factory data to the database.

// Create a single App\Models\User instance...
$UserModel = User::factory()->create();
 
// Create three App\Models\User instances...
$UserModelCollection = User::factory()->count(3)->create();

Factory Relationships

use App\Models\Post;
use App\Models\User;

// Create 1 user and 3 posts to the database
$UserModel = User::factory()
  ->has(Post::factory()->count(3))
  ->create();

Reference