Laravel 5.5 Eloquent WhenLoaded Relations

The Laravel 5.5 documentation in the Conditional Relationships section says:

whenLoaded method can be used to conditionally load relationships

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 role key is completely removed from the resource response before it is sent to the client because the connection was not loaded.

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

+5
source share
1 answer

Lively Download

At the time of the request for the parent model, Eloquent may interact with an impatient load.

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

Lazy Eager Loading

The desire to load relationships after the parent model has already been restored

 $user->load('roles'); 

Download Missing Links

Loading a relationship only when it has not yet been downloaded

 $user->loadMissing('roles'); 
+3
source

Source: https://habr.com/ru/post/1272120/


All Articles