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)?
Just save the model after updating:
$project->update($data);
$project->save();
return $project->client;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With