amir amir - 1 year ago 70
PHP Question

get limited records in eloquent

First , i'm sorry for my english.

I have two tables:


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


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.

return $query->skip(0)->take(4);

Answer Source

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;