Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - Updating model does not update relationships immediately

I ran into an interesting issue today while trying to update a model with a simple hasOne relationship. I was doing the following:

public function update(MyRequest $request, $id)
{
    $project = Project::find($id);
    $data = $request->all(); //has a client_id
    $project->update($data);
    return $project->client; //Project model holds this hasOne relationship
}

The issue is that $project->client returned from the update function is still the old version of the client. Shouldn't the $project->update(...) refresh those relationships? The code that we have working now is:

public function update(MyRequest $request, $id)
{
    $project = Project::find($id);
    $data = $request->all(); //has a client_id
    $client = Client::find($data['client_id']);
    $project->update($data);
    $project->client()->associate($client);
    return $project->client; //Project model holds this hasOne relationship
}

At this point we are all good. So, is the later version of the function the correct way to do this (IE get a refreshed version of the client object)?

like image 287
Greg Avatar asked May 18 '15 17:05

Greg


1 Answers

Just save the model after updating:

$project->update($data);
$project->save();

return $project->client; 
like image 97
saadel Avatar answered Oct 31 '22 03:10

saadel