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)?
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With