Skip to content
Advertisement

Laravel paginate pivot tables

I have collections which contains custom products I need to paginate those collections products but I receive error.

data

  1. With this query I can get my collection and it’s products but I’m not able to paginate products.

$collection = Collection::where(‘slug’, $slug)->where(‘status’, ‘active’)->with(‘products’)->first();

  1. With this query I receive error

$collection = Product::with(‘collections’)->whereHas(‘collections’, function($query) use($slug) { $query->where(‘slug’, $slug)->where(‘status’, ‘active’)->first(); });

Error

JavaScript

Code

Product model

JavaScript

Collection model

JavaScript

CollectionProduct model

JavaScript

Controller default query

JavaScript

Question

  1. How can I get my collection products with pagination ability?

Advertisement

Answer

Couple things:

You are trying to call the first() method inside of a relationship query in this line:

$collection = Product::with(‘collections’)->whereHas(‘collections’, function($query) use($slug) { $query->where(‘slug’, $slug)->where(‘status’, ‘active’)->first(); });

The methods first() and get() are used to execute the query, so you should keep them at the end of the chain of eloquent methods:

JavaScript

https://laravel.com/docs/5.7/eloquent#retrieving-models

However, if you want to paginate the list of products, then what you really want is the paginate() method:

JavaScript

https://laravel.com/docs/5.7/pagination

Also, the collections() method on your Product model has product_id listed as the join table, and is joining to the CollectionProduct model instead of the Collection model.

Try this instead for your Product model:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement