Search code examples
sqllaraveleloquenteager-loading

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(["*"]    
}]);

Solution

  • Just needed to add the primary key column and that worked fine.

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

    This way any constraints can be added to the query.