amir amir - 4 months ago 15
PHP Question

get limited records in eloquent

First , i'm sorry for my english.

I have two tables:

Users


class Users extends Model {
public function posts(){
return $this->hasMany('App\posts','user_id');
}
}


and
posts


class posts extends Model{
public function users(){
return $this->belongsTo('App\Users','user_id');
}
}


Each users has many posts.

I want take only 4 posts of each users.

I tested this code, but it does not work.

Users::with(['posts'=>function($query){
return $query->skip(0)->take(4);
}])->get();

Answer

You can't limit results on eager loads

However, you can run it like this:

return Users::with('posts')->get()->map(function ($users) {
    $users->posts = $users->setRelation('posts', $users->posts->take(4));
    return $users;
});