Defining Laravel foreign keys with Model Factories, One to One & One to Many Relationships without creating unnecessary models Defining Laravel foreign keys with Model Factories, One to One & One to Many Relationships without creating unnecessary models laravel laravel

Defining Laravel foreign keys with Model Factories, One to One & One to Many Relationships without creating unnecessary models


So here is my solution:

The example deals with:

  • Users & Profiles (for illustrating One to One relationships)
  • Users & Posts (for illustrating One to Many relationships)

    // ONE TO ONE relationship (with Users already created)$factory->define(App\Profile::class, function (Faker\Generator $faker) {    return [        'user_id' => $faker->unique()->numberBetween(1, App\User::count()),        // Rest of attributes...    ];});// ONE TO MANY relationship (with Users already created)$factory->define(App\Posts::class, function (Faker\Generator $faker) {    $users = App\User::pluck('id')->toArray();    return [        'user_id' => $faker->randomElement($users),        // Rest of attributes...    ];});


Here is a solution to make relationships that is way better than assigning random Users, especially if you need to send extra information to this model.

$factory->define(App\Post::class, function (Faker\Generator $faker) {    $user = factory('App\Models\User')->create(['email' => 'email@test.com',]);    // do your relationships here (...)    return [        'user_id' => $user->id,        'title'   => $faker->sentence,        'body'    => $faker->paragraph,        ];    }

And I saw another example with the use of anonymous function

$factory->define(App\Post::class, function (Faker\Generator $faker) {    return [        'user_id' => function () {            return factory(App\User::class)->create()->id;        },        'title' => $faker->sentence,        'body'  => $faker->paragraph,    ];}

Source: https://laracasts.com/series/laravel-from-scratch-2017/episodes/22