Skip to content

Instantly share code, notes, and snippets.

@deligoez
Created November 8, 2021 06:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deligoez/db7e992bda08585cdce221fbc5fb25d6 to your computer and use it in GitHub Desktop.
Save deligoez/db7e992bda08585cdce221fbc5fb25d6 to your computer and use it in GitHub Desktop.
CityFactory
<?php
namespace Database\Factories;
use App\Models\City;
use App\Models\Country;
use App\Models\Region;
use Illuminate\Database\Eloquent\Factories\Factory;
class CityFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = City::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition(): array
{
return [
'name' => $this->faker->city(),
'code' => $this->faker->numerify('###'),
'latitude' => $this->faker->latitude(),
'longitude' => $this->faker->longitude(),
'country_id' => Country::factory()->lazy(),
'region_id' => Region::factory()->lazy(),
];
}
public function country(null|int|Country $country): self
{
return $this->state(function (array $attributes) use ($country) {
$country = $country === null
? Country::factory()->lazy()
: ($country instanceof Country ? $country->id : $country);
return ['country_id' => $country];
});
}
public function region(null|int|Region $region): self
{
return $this->state(function (array $attributes) use ($region) {
$country = $attributes['country_id'] ?? Country::factory()->lazy();
$region = $region === null
? Region::factory()->lazy(['country_id' => $country])->id
: ($region instanceof Region ? $region->id : $region);
return [
'region_id' => $region,
'country_id' => $country,
];
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment