MvdP
MvdP

Reputation: 271

Laravel: Eloquent how to update a model and related models in one go

Does anyone know if it is possitble to do the folowing:

Let's say we have a model called User and a model calledd BestFriend. The relation between the User and the best friend is 1:1.

I would like for these cases be able to do something like this, change my city and the city of my friend at the same time.

$me = User::find(1);

$me->update(array(
'city' => 'amsterdam',
'bestfriend.city' => 'amsterdam'
));

So basically I would like to know if Eloquent is smart enough to understand the relationship based on the array key 'bestfriend.city'.

Thanks in advance for any help!

Update:

Found the solution on the Laravel forums but im posting it here as well if someone else is looking for the same thing :)

In the model you add

// In your model...
public function setBestFriendArrayAttribute($values)
{
    $this->bestfriend->update($values);
}

And then you can call it like this

$me->update(array(
    'city' => 'amsterdam',
    'BestFriendArray' => array(
        'city' => 'amsterdam'
    )
));

Works like a charm!

Upvotes: 27

Views: 35381

Answers (3)

Marek
Marek

Reputation: 2731

If you want to save same city name to both entities this will do the job:

$me = User::find(1);

$me->update(array(
    'city' => 'amsterdam',
));

And in your model:

public function setCityAttribute($value) 
{
    $this->attributes['city'] = $value;
    $this->bestfriend->city= $value;
    $this->bestfriend->save();
}

Upvotes: 0

dakine
dakine

Reputation: 699

You don't need to set it on your model. You can do it on your controller like this.

$me = User::find(1)->bestFriend()->update(array(
'city' => 'amsterdam',
'bestfriend.city' => 'amsterdam'
));

I just modified your update a little bit.

Upvotes: 12

user1669496
user1669496

Reputation: 33048

Eloquent is pretty smart, but I don't believe it can do that. You would have to update User and BestFriend independently. But once you've done that, Eloquent does have methods for attaching the two.

$me = User::find(1);
$bff= BestFriend::find(1);

$me->city = 'amsterdam'; 
$bff->city = 'amsterdam';

$me->bestfriend()->associate($bff);

This is of course assuming your User model has a function that looks like...

public function bestfriend()
{
    return $this->hasOne('BestFriend');
}

Upvotes: 4

Related Questions