Search code examples
laraveleloquenteager-loadingeloquent-relationship

Laravel Eager-loading works only when calling attribute


I've defined my Slot model to load the relations from User model like so :

public function userAssignedFull(): HasOne {
    return $this->hasOne(User::class,'id','user_assigned');
}

('slots' table contains 'user_assigned' field by which I connect to User records on 'id')

The following code finds Slot model but without 'userAssignedFull'. I get only the user ID in 'user_assigned'.

  $slot = Slot::with('userAssignedFull')->find($slot_id);

But calling this afterward returns me the wanted relation:

$fullUserModel = $slot->userAssignedFull;

Can anyone tell me what am I doing wrong ?


Solution

  • Builder::with() returns the Builder instance.

    So you have to call $slot->userAssignedFull; to get the collection of data.

    From the docs:

    When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property.

    And this $slot->userAssignedFull; is your "first access the property".