Last active
March 14, 2020 12:34
-
-
Save palypster/999c0cb3ce20eb811625f76dba23121f to your computer and use it in GitHub Desktop.
Cascading Laravel Factories - Cascading Factory with states
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** @var \Illuminate\Database\Eloquent\Factory $factory */ | |
use App\Client; | |
use App\Project; | |
use Faker\Generator as Faker; | |
$factory->define(Project::class, function (Faker $faker) { | |
return [ | |
'title' => $faker->sentence, | |
]; | |
}); | |
$factory->state(Project::class, 'relations-cascade', function (Faker $faker) { | |
// cascade all dependent relations creating new objects | |
return [ | |
'client_id' => factory(Client::class)->state('relations-cascade')->create()->getKey() | |
]; | |
}); | |
$factory->state(Project::class, 'relations-reuse', function (Faker $faker) { | |
// cascade all dependent relations reusing existing objects | |
return [ | |
'client_id' => Client::query()->inRandomOrder()->first()->getKey() | |
]; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment