Search code examples
laraveleloquent-relationship

Create and associate with Eloquent in Laravel


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.

  1. Add the 'country_id' to AddresseModel $fillable property, and then Country::create($request->address);
  2. Use new Address() and then assign fields to matching object's properties. Finally save();
  3. Allow 'country_id' to be nullable, make 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)

Solution

  • You can do something like this:

    $country = Country::find($request->country_id);
    $address = $country->addresses()->create([
        'city' => 'Barcelona',
        ...
    ]);