Laravel Eloquent Limit in Eager Loading

Laravel Eloquent Limit
Spread the love

Sometimes may we need to show limited data that are coming from eager loading in Laravel. In this Laravel eloquent tips and tricks tutorial, I am going to show you how we can limit our eager loading result. Let’s assume a scenario. You have a Category model and a Movie model. Each category has multiple movies. So you define hasMany relationships in the Category model. Now you would like to fetch all categories as well movies but the number of movies is limited. It could be five or ten or whatever.

Using typical relationships you can’t able to do that. To do that, you have to install another third-party package. That is the https://github.com/staudenmeir/eloquent-eager-limit . Well, let’s see the implementation of this package.

Well, I assume that you have a category model and a movie model. Now install this package using this command.

Laravel Eloquent Limit

composer require staudenmeir/eloquent-eager-limit:"^1.0"

Well, after successfully installing this package, you can see a bit modified in the composer.json file.

   "require": {
      // another packages 
        "staudenmeir/eloquent-eager-limit": "^1.0",
    },

Well, now go to the Category model then define a hasMany method as well as an implement with a trait. Your code looks like this below.

App/Models/Category.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 Category extends Model
{
    use HasFactory, HasEagerLimit;
    protected $guarded = [];

    public function movies(): HasMany
    {
        return $this->hasMany(Movie::class)->latest()->take(2);
    }
}

Well, you can see that I have implemented a trait that is HasEagerLimit. This trait is coming from that package which I have installed before.

Well, now go to the Product model and implement it with the same trait. So then your code looks like this below.

App/Models/Movie.php

class Movie extends Model
{
    use HasFactory, HasEagerLimit;
}

Well, all kinds of stuff have been done. Now time to check this model data with limited egar load. Let’s create an API or route to check this model relationship.

web.php

Route::get('test',function(){
     return Category::with('movies')->get();
});

Or you can write this way.

Route::get('test',function(){
     return Category::with(['movies' => function ($query) {
            $query->latest()->limit(10);
       }])->get();
});

Well, your responses data looks like below. You can change the limit value according to your desired data.

[
  {
    "id": 1,
    "name": "Horror",
    "slug": "horror",
    "image": "https://picsum.photos/seed/picsum/200/300",
    "created_at": "2022-03-13T15:00:25.000000Z",
    "updated_at": "2022-03-13T15:00:25.000000Z",
    "movies": [
      {
        "id": 1,
        "category_id": 1,
        "name": "Expedita earum eius excepturi.",
        "slug": "accusantium-quisquam-quisquam",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 2,
        "description": "Doloribus maiores.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      },
      {
        "id": 6,
        "category_id": 1,
        "name": "Modi a nostrum magni.",
        "slug": "ea-a-rem-sapiente",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 1,
        "description": "Ut officia cumque.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      },
      {
        "id": 10,
        "category_id": 1,
        "name": "Culpa hic qui.",
        "slug": "officiis-rem-nisi",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 3,
        "description": "Voluptas tenetur.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      },
      {
        "id": 15,
        "category_id": 1,
        "name": "Ullam illum quia voluptatibus.",
        "slug": "omnis-commodi-nihil",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 1,
        "description": "Est ullam quia et.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      }
    ]
  },
  {
    "id": 2,
    "name": "Action",
    "slug": "action",
    "image": "https://picsum.photos/seed/picsum/200/300",
    "created_at": "2022-03-13T15:00:25.000000Z",
    "updated_at": "2022-03-13T15:00:25.000000Z",
    "movies": [
      {
        "id": 2,
        "category_id": 2,
        "name": "Voluptas sed quo.",
        "slug": "rem-saepe-quas-quidem",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 3,
        "description": "Quo itaque corrupti.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      },
      {
        "id": 8,
        "category_id": 2,
        "name": "Maiores in amet dolorem.",
        "slug": "repudiandae-rerum-molestias",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 1,
        "description": "Est rerum.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      },
      {
        "id": 9,
        "category_id": 2,
        "name": "Modi nesciunt.",
        "slug": "odit-aut-voluptatem",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 3,
        "description": "Harum distinctio.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      },
      {
        "id": 13,
        "category_id": 2,
        "name": "Enim aliquam explicabo.",
        "slug": "quia-omnis",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 1,
        "description": "Aut ut quia nemo.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      }
    ]
  },
  {
    "id": 3,
    "name": "Sci-Fi",
    "slug": "sci-fi",
    "image": "https://picsum.photos/seed/picsum/200/300",
    "created_at": "2022-03-13T15:00:25.000000Z",
    "updated_at": "2022-03-13T15:00:25.000000Z",
    "movies": [
      {
        "id": 3,
        "category_id": 3,
        "name": "Quia ex harum.",
        "slug": "consequatur-voluptas-sint",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 3,
        "description": "Adipisci vel.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      },
      {
        "id": 4,
        "category_id": 3,
        "name": "Inventore molestiae laboriosam nulla dolor.",
        "slug": "eum-rerum-iusto-fuga",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 1,
        "description": "Perspiciatis.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      },
      {
        "id": 5,
        "category_id": 3,
        "name": "Est sed repellat ducimus.",
        "slug": "autem-debitis-id-atque",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 3,
        "description": "Dolorum sunt.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      },
      {
        "id": 7,
        "category_id": 3,
        "name": "Qui rerum voluptas.",
        "slug": "nesciunt-sit-facere-reprehenderit",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 2,
        "description": "Vitae commodi animi.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      },
      {
        "id": 12,
        "category_id": 3,
        "name": "Debitis iure quod assumenda.",
        "slug": "tenetur-voluptas-saepe-dolor-delectus",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 1,
        "description": "Qui ea tempore hic.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      },
      {
        "id": 14,
        "category_id": 3,
        "name": "Assumenda facilis perferendis corrupti.",
        "slug": "a-est-minima-doloremque",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 3,
        "description": "Et nulla sed.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      }
    ]
  },
  {
    "id": 4,
    "name": "Romantic",
    "slug": "romantic",
    "image": "https://picsum.photos/seed/picsum/200/300",
    "created_at": "2022-03-13T15:00:25.000000Z",
    "updated_at": "2022-03-13T15:00:25.000000Z",
    "movies": [
      
    ]
  },
  {
    "id": 5,
    "name": "Fantasy",
    "slug": "fantasy",
    "image": "https://picsum.photos/seed/picsum/200/300",
    "created_at": "2022-03-13T15:00:25.000000Z",
    "updated_at": "2022-03-13T15:00:25.000000Z",
    "movies": [
      {
        "id": 11,
        "category_id": 5,
        "name": "Nobis sit est quia.",
        "slug": "saepe-cupiditate-consequatur",
        "image": "https://picsum.photos/seed/picsum/200/300",
        "duration": 1,
        "description": "Totam excepturi.",
        "created_at": "2022-03-13T15:00:25.000000Z",
        "updated_at": "2022-03-13T15:00:25.000000Z"
      }
    ]
  }
]
Read More : Multiple API Authentication using JWT in Laravel 9

Spread the love

About Anisur Rahman Shahin

Hello. My name is Shahin. I'm a tech enthusiast guy. Personally, I’m Optimistic and always in hurry kinda person. I'm a freelance web developer. I am working at Zakir Soft as Laravel Developer. My Portfolio website: https://devshahin.com/

View all posts by Anisur Rahman Shahin →

Leave a Reply

Your email address will not be published.