Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.5 Eloquent WhenLoaded relationship

On the Laravel 5.5 documentation, under Conditional Relationships, it says

whenLoaded method may be used to conditionally load a relationship

I tried in my code

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'roles' => Role::collection($this->whenLoaded('roles')),
        'remember_token' => $this->remember_token,
    ];
}

According to the documentation, the roles key is removed from the resource response entirely before it is sent to the client because the relationship hasn't been loaded.

How do I load a relationship? How do I determine if a relationship is loaded? In this case how do I load Role (model)?

like image 769
Nucleus Avatar asked Sep 26 '17 08:09

Nucleus


People also ask

Does Laravel 8 have one relation?

hasOne relationship in laravel is used to create the relation between two tables. hasOne means create the relation one to one. For example if a article has comments and we wanted to get one comment with the article details then we can use hasOne relationship or a user can have a profile table.


1 Answers

Eager Loading

Eloquent can "eager load" relationships at the time you query the parent model.

$user = App\User::with('roles')->find($id);

Lazy Eager Loading

To eager load a relationship after the parent model has already been retrieved

$user->load('roles');

Load Missing Relationships

To load a relationship only when it has not already been loaded

$user->loadMissing('roles');
like image 107
kerrin Avatar answered Nov 07 '22 06:11

kerrin