Reputation: 1157
Can I create and associate related model in-line? For example
Let be table countries with ids and names. For instance 171 | Poland
.
Table addresses has column country_id as foreign key, but not null and columns such as city, street and others.
In AdressModel, $fillable property is set as well.
And now, to create new Address from request, I know three ways to do it.
new Address()
and then assign fields to matching object's properties. Finally save()
;Country::create($request->address)
and the call associate() on given relation method, country() in that case.Is there a way to do that inline without nullable(), something like:
$country = Country::find($request->country_id);
$address = Address::create($request->address)->country()->associate($country)
Upvotes: 0
Views: 114
Reputation: 908
You can do something like this:
$country = Country::find($request->country_id);
$address = $country->addresses()->create([
'city' => 'Barcelona',
...
]);
Upvotes: 2