Laravel Eloquent Limit Eager Loading Data Example

Hello Artisan,

In this Laravel eloquent tips and tricks tutorial, I am going to show you how we can limit our eager loading result. Sometimes may we need to show limited data that are coming from eager loading in Laravel. So this Laravel limit relationship results tutorial, you will learn it.

To create this query, I will use staudenmeir/eloquent-eager-limit the package is pretty cool. You can use this limit with your any eager loading in Laravel eloquent relationship. See the below example:

 

eloquent-eager-loading-limit-query-example

 

Suppose we have a Post model like:

App\Models\Post.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Staudenmeir\EloquentEagerLimit\HasEagerLimit;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Post extends Model
{  
    use HasFactory, HasEagerLimit;

    protected $guarded = [];
    
    public function comments() : HasMany
    {
        return $this->hasMany(Comment::class)->latest()->limit(3);
    }
}

 

And we have a comment model like:

App\Models\Comment.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Staudenmeir\EloquentEagerLimit\HasEagerLimit;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Comment extends Model
{
    use HasFactory, HasEagerLimit;

    protected $guarded = [];
    
}

 

Now install this composer package by the following command:

composer require staudenmeir/eloquent-eager-limit

 

Now you will be able to limit your eloquent eager loading query like below:

public function comments() : HasMany
{
  return $this->hasMany(Comment::class)->latest()->limit(3);
}

 

Now call it in the controller like:

Route::get('/',function(){

    return Post::with('comments')->get();
    
});

 

Or you can limit your query like below:

$users = User::with(['posts' => function ($query) {
    $query->latest()->limit(10);
}])->get();

 

Read also: How to Use Enum Data Type in Laravel Migration

 

Hope this can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js