Search code examples
phplaraveleloquenteloquent-relationship

How to specify columns we want from eager load


I am using beyondcode/laravel-comments (https://github.com/beyondcode/laravel-comments) and I try to specify columns I want to get from commentator. here is the code:

$comment = $post->comments()->with('commentator', function ($query) {
        $query->select('commentator.name', 'commentator.email');
        //or $query->select('users.name', 'users.email');
})->latest();

I am getting error that said

Undefined table: 7 ERROR:  missing FROM-clause entry for table "commentator" // or users

How can I fix it? thanks


Solution

  • As in the documentation, just do your eager load like this to specify columns, no function needed:

    $comment = $post
        ->comments()
        ->with('commentator:id,name,email')
        ->latest();
    

    If you do need to use a callback to alter the eager load, you would have to use an array as shown in the documentation:

    $comment = $post
        ->comments()
        ->with([
            'commentator' => fn ($q) => $q->select('id', 'name', 'email')
        ])
        ->latest();