I'm having a problem with displaying results from my db using eloquent in laravel 5.4. I just want to specify a columns that I want to be in my results. So in my case the record is relation to another tables which I want also to specify a column that I need. Please check my eloquent:
return User::with(['images' => function($q){
$q->select('user_id as userId','image_name','url');
}])
->orderBy('id', 'asc')
->select(['id as userId','name','email'])
->paginate(10);
and here's my hasMany() relations in my model:
public function images(){
return $this->hasMany('Images', 'user_id', 'id');
}
The problem with this code the images are always null. Any idea? Thanks in advance.
Give this a try:
return User::with(['images' => function($q){
$q->select('id', 'image_name','url');
}])
->orderBy('id', 'asc')
->select(['id','name','email'])
->paginate(10);
You need to select the relationship key for it to find results.