Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select specific fields in Eloquent eager loading not working

I have a Notifications model that belongs to a User. I want to load the user when a collection of notifications is selected and only load the model with names and emails. However, when using the select method, the query returns null.

$notifications->load(['user' => function($query){
    $query->select(["name","email"]);
}]);

If the parameter for select() method is given as below, it gives all the fields:

$notifications->load(['user' => function($query){
    $query->select(["*"]    
}]);
like image 375
Birendra Gurung Avatar asked May 31 '18 11:05

Birendra Gurung


1 Answers

Maybe selecting the fields like this works out:

$notifications->load('user:id,name,email');

What you are trying is designed to add constraints, not to select some fields

like image 152
GaimZz Avatar answered Sep 20 '22 10:09

GaimZz