Created
November 8, 2021 06:42
-
-
Save deligoez/db7e992bda08585cdce221fbc5fb25d6 to your computer and use it in GitHub Desktop.
CityFactory
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 | |
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