Home > OS >  Laravel offset and limit on with()?
Laravel offset and limit on with()?

Time:06-03

When I do this, it doesn't do what I expect - get the "paginated" result of the related comments per post. Below, it only returns the comments of the first post.

   Post::with(['comments' => function($query) {
       $query->offset(0)->limit(10);
   }])->get()

Result:

  [
       {
          ...
          "comments" : [
             [Comment], [Comment], [Comment]  # <-- Only this post has comments.
          ]
       }, 

       {
           ...
           "comments" : [

           ]               # <-- Other posts do not have comments. =(
       }
  ]

I aim to have each array item above to have a max of 10 comments in "paginated" manner using offset and limit on with().

Is it possible to do this in Laravel?

CodePudding user response:

offset(0) can be omitted

Album::with(['images' => function ($query) {
    $query->limit(10);
}])->get();

if you need to have ONLY posts that have comments only you can do it like this with whereHas:

    Post::whereHas('comments', function($query) {
       $query->whereNotNull('image')->limit(10);
   }])->get()

CodePudding user response:

Get Posts with Comments - limit number of comments to 10

Post::with(['comments' => fn($query => $query->limit(10)])->get();

Only get those Posts which have at least 1 Comment and limit the maximum number of comments to 10

Post::with(['comments' => fn($query) => $query->limit(10)])
    ->has('comments')
    ->get();

Only get those Posts which have at least 5 Comments and limit the maximum number of comments to 10

Post::with(['comments' => fn($query) => $query->limit(10)])
    ->has('comments', '>=', 5)
    ->get();

Get only those Posts which have at least 5, Comments containing "lara", and limit the maximum number of comments to 10

Post::with(['comments' => fn($query) => $query->limit(10)])
    ->whereHas(
        //Relation
        'comments', 

        //Constrain to filter comments - only comments which contain "lara"
        fn($query) => $query->where('content', 'like', 'lara%'), 
       
        //Comparison Operator indicates minimum
        '>=', 

        //Along with operator says minimum of 5 records which fulfil the constrain
        5
    )
    ->get();
  • Related