2
votes

I have a classic one-to-many relationships, and I am trying to save the model of the belongsTo side.

The 2 models have these relationships:

// Model myModel
function domicile()
{
    return $this->belongsTo('App\Address', 'domicile_id');
}

// Model Address
function myModels()
{
    return $this->hasMany('App\MyModel', 'domicile_id');
}

This is what I am tryng to do to save it:

$myModel->domicile()->save($my_array);

With this code I get the error:

Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::save()

if I use this code (without the brackets):

$myModel->domicile->save($my_array);

I do not get any error but the model is not saved.
I know there is the method associate, but I need to update an existent record, not to save a new one.

3

3 Answers

2
votes

Because $myModel->domicile()->save($my_array); is totally different to $myModel->domicile->save($my_array); :

  1. $myModel->domicile() will produce a BelongsTo object, doesn't support the save because save is a method of HasMany instances, instead for BelongsTo instances you should use associate(YourModel)

  2. $myModel->domicile will produce a Model object of the associated element, which support the save(array) method, but that array is a options array, as api says https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Model.html#method_save

So in other words, if you have a one (address) to many (domicile) relation, if you want to associate to the address one or many domiciles, you have to use save or saveMany (https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Relations/HasMany.html#method_save), instead if you want to associate to a domicile a address, you should use associate (https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Relations/BelongsTo.html#method_associate)... keep in mind that if you want to do this, you should call the properties with the brackets, in order to have back a HasMany object or a BelongsTo object, and not a Model or a Collection (which you will get if you call the properties without the brackets)

1
votes

Instead of using the save function, in order to save a belongsTo relationships you have to use the fill function.

In this way:

$myModel->domicile->fill($my_array);
$myModel->domicile->save();
1
votes

You must use associate() + save() in order to store a BelongsTo relationship:

$myModel->domicile()->associate($domicile);
$myModel->save();

See Laravel Docs