When testing your application or seeding your database, you need to insert records into the database. Instead of manually specifying the value of each column, Laravel lets you define a set of default attributes for each Eloquent model using model factories.All new Laravel applications include database/factories/UserFactory.php as a starting example.
namespace Database\Factories;use Illuminate\Database\Eloquent\Factories\Factory;use Illuminate\Support\Facades\Hash;use Illuminate\Support\Str;class UserFactory extends Factory{ // Cached to avoid re-hashing the same password on every call protected static ?string $password; public function definition(): array { return [ 'name' => fake()->name(), 'email' => fake()->unique()->safeEmail(), 'email_verified_at' => now(), 'password' => static::$password ??= Hash::make('password'), 'remember_token' => Str::random(10), ]; }}
Via the fake() helper, factories have access to the Faker PHP library for generating random data.
Change your application’s Faker locale by updating the faker_locale option in config/app.php.
When your model uses the HasFactory trait, Laravel automatically finds the corresponding factory by looking in the Database\Factories namespace for a class named after the model suffixed with Factory.If the naming convention doesn’t apply, use the UseFactory attribute to specify the factory explicitly:
use Illuminate\Database\Eloquent\Attributes\UseFactory;use Database\Factories\Administration\FlightFactory;#[UseFactory(FlightFactory::class)]class Flight extends Model{ // ...}
Register afterMaking and afterCreating callbacks to perform additional tasks after the model is made or created.
namespace Database\Factories;use App\Models\User;use Illuminate\Database\Eloquent\Factories\Factory;class UserFactory extends Factory{ public function configure(): static { return $this->afterMaking(function (User $user) { // Runs after make() — model not yet in the database })->afterCreating(function (User $user) { // Runs after create() — model is persisted }); } // ...}
You can also register callbacks inside state methods for state-specific side effects:
public function withProfile(): static{ return $this->state(fn (array $attributes) => []) ->afterCreating(function (User $user) { $user->profile()->create([ 'bio' => fake()->paragraph(), ]); });}
Use recycle() to reuse a single model instance across all relationships created by the factory:
// Both Ticket and Flight use the same Airline instanceTicket::factory() ->recycle(Airline::factory()->create()) ->create();// Pick randomly from a collection$airlines = Airline::factory()->count(3)->create();Ticket::factory()->count(10)->recycle($airlines)->create();