Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel factory foreign key


Laravel factory foreign key


To set a foreign key in a Laravel factory, you can use the `state()` method to define a state that sets the foreign key value. Here's an example:

php
// database/factories/PostFactory.php
$factory->define(App\Models\Post::class, function (Faker\Generator $faker) {
    return [
        'title' => $faker->sentence,
        'content' => $faker->paragraph,
    ];
});

$factory->state(App\Models\Post::class, 'with_user', function (array $attributes, Faker\Generator $faker) {
    return [
        'user_id' => function () {
            return factory(App\Models\User::class)->create()->id;
        },
    ];
});

In this example, we define a `'with_user'` state for the `Post` model that sets the `user_id` foreign key to the ID of a newly created `User` model.

You can then use this state in your tests:

php
// tests/Feature/PostTest.php
public function testCreatePostWithUser()
{
    $post = factory(App\Models\Post::class)
        ->states('with_user')
        ->create();

    $this->assertNotNull($post->user);
}

This will create a `Post` instance with a related `User` instance.

Alternatively, you can use the `for()` method to associate the created model with an existing model:

php
// tests/Feature/PostTest.php
public function testCreatePostForUser()
{
    $user = factory(App\Models\User::class)->create();

    $post = factory(App\Models\Post::class)
        ->for($user)
        ->create();

    $this->assertEquals($user->id, $post->user_id);
}

In this example, we create a `User` instance first, and then use the `for()` method to associate the created `Post` instance with the `User` instance.

By using factory states and the `for()` method, you can easily set up foreign key relationships in your Laravel factories, making your tests more expressive and maintainable.

Citations:
[1] https://ahmedash.dev/blog/laravel-core-bits/factory-relations-deep-dive/
[2] https://cosme.dev/tip/laravel-tip-belongs-to-relationships-in-factories
[3] https://en.wikipedia.org/wiki/Laravel
[4] https://stackoverflow.com/questions/58846325/laravel-adding-relationships-to-a-factory-created-model
[5] https://laravel.com/api/8.x/Illuminate/Database/Eloquent/Factories/Factory.html