Laravel 5 - Updated model doesn't update relationships immediately

I ran into an interesting problem today while trying to update a model with a simple hasOne relationship. I did 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 problem is that what $project->client

is returned from the function update

is still the old version of the client. Should $project->update(...)

this relationship be renewed? The code we are currently working on:

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 we are all good. So, is a later version of the function the correct way to do this (IE get an updated version of the client object)?

+3


source to share


1 answer


Just save the model after updating:



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

return $project->client; 

      

+2


source