Search code examples
phplaraveleloquentrelationship

Laravel after save model need to refresh it to use the relationships


I'm struggling with weird problem, don't know if it should considered as a bug.

I have this code on update process:

    // initial $invoice->user_updated_id = 1

    $invoice = $this->find($id); // Invoice::findOrFail($id)
    $userId = Auth::user()->id; // $userId = 2
    $request = array_merge($request, ['user_updated_id' => $userId]);
    $invoice->fill($request);
    $invoice->save();

    Log::info('Attribute: ' . $invoice->user_updated_id);
    Log::info('Relation: ' . $invoice->userUpdated->id); // Basic relationship to User model.

The output is:

local.INFO: Attribute: 2
local.INFO: Relation: 1

Why after saving the model the relationship is still getting the old model?

If I rewrite the code with:

    // initial $invoice->user_updated_id = 1

    $invoice = $this->find($id);
    $userId = Auth::user()->id; // $userId = 2
    $request = array_merge($request, ['user_updated_id' => $userId]);
    $invoice->fill($request);
    $invoice->save();
    $invoice->refresh();

    Log::info('Attribute: ' . $invoice->user_updated_id);
    Log::info('Relation: ' . $invoice->userUpdated->id); // Basic relationship to User model.

The output is:

local.INFO: Attribute: 2
local.INFO: Relation: 2

Solution

  • Your refresh call works but it's also redundant because it refreshes the main model you've just saved before, and you probably don't want to do this because its data are good. To refresh only relationships, you can use load('userUpdated') or loadMissing('userUpdated') methods. load loads some relationships even if they are already loaded whereas loadMissing does it only once.