Nucleus
Nucleus

Reputation: 397

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)?

Upvotes: 7

Views: 5637

Answers (1)

kerrin
kerrin

Reputation: 3452

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');

Upvotes: 6

Related Questions