Search code examples
phplaravel-5.3

Retrieve specific field while doing eager loading in laravel


I am new to laravel and I am using laravel 5.3 I am having a user table which is made up of 18 fields. Any time I run this line: $article->load('comments.user', 'comments.replies.user');, I am getting all the 18 fields. Is there any possibility to retrieve only 3 fields (name, username and id) ?

I have spent some time searching on google but the answer I found, does not work:

$article->load(array('comments.user' => function($query) {
  $query->select('id', 'name', 'username');
}));

Solution

  • The line $article->load('comments.user', 'comments.replies.user'); can be changed to the following lines of code where the desired fields can be specified

    return $article->load(
        array(
            'comments.user' => function($query) {
                $query->select('id', 'name', 'username')->get();
            },
            'comments.replies.user' => function($query) {
                $query->select('id', 'name', 'username')->get();
            }
        )
    );