eloquenteager-loadinglaravel-5.7

Why select is not working in eloquent in Laravel 5.7?


The following code is working fine:

Post::with(['user'])
    ->get();

but when I try to filter it using select, it returns null in user relations.

Post::with(['user' => function($query){
    $query->select('name');
}])
->select('id', 'slug', 'title', 'body', 'created_at')
->get();

relation inside User Model:

public function posts()
{
    return $this->hasMany('App\Post');
}

relation inside Post Model:

public function user()
{
   return $this->belongsTo('App\User', 'user_id');
}

Solution

  • You have to select the foreign key (posts.user_id) and the owner key (users.id):

    Post::with(['user' => function($query){
        $query->select('id', 'name');
    }])
    ->select('id', 'slug', 'title', 'body', 'created_at', 'user_id')
    ->get();
    

    You can also use this shorter version:

    Post::with('user:id,name')
        ->select('id', 'slug', 'title', 'body', 'created_at', 'user_id')
        ->get();