Sometimes we need to fetch only limited relationship data in laravel application. But the problem is, we can not do it with default laravel relationship system. So we need to customize our query or we can use packages. Using staudenmeir/eloquent-eager-limit package, we can easily do laravel limit relationship results.

So in this laravel eloquent with relationship limit tutorial, I will discuss how to limit relationship result in laravel using this staudenmeir/eloquent-eager-limit package. So let's see the example code and steps of laravel limit relationship results tutorial.

laravel-limit-relationship-results

First of all, we need to install this staudenmeir/eloquent-eager-limit package. So run the below command to install this package:

composer require staudenmeir/eloquent-eager-limit

 

Now update the Post model like that. Assume we have a Comment model and there is a relationship between post and comment. Note that we have to use the HasEagerLimit trait in the Post model.

App\Models\Post.php

<?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);
    }
}

 

Now just call it from the controller like:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class TutorialController extends Controller
{   
    /**
     * Tutorial from LARAVELIA
     */
    public function index()
    {   
        return Post::with('comments')->get();
    }
}

 

Read also: Calculate Relational Average Using WithAvg In Laravel

 

Conclusion

In this laravel limit relationship results tutorial,  I have tried my best to let you know laravel eloquent with relationship limit. Hope now after completing this how to limit relationship result in laravel tutorial, you will know laravel eloquent limit relationship result.