tehseen's avatar

Get all products by category slug with paginate..

Hi,

I am having issue in getting all products by category slug in category single page the products data is fine but i need it with pagination to only show 12 on one page here is the below code i write.

Note: product and category have many to many relationship

$category = Category::where('slug', '=', $slug)->firstOrFail();
$categoryProducts = $category->products->paginate(12);

the above is works fine for me to get category all products but i need it with pagination any help please.

Regards

0 likes
5 replies
tisuchi's avatar

@tehseen

Have you tried this?

$category->products()->paginate(12);

Ofcourse there are some other ways to figure it out.

1 like
Sergiu17's avatar

Hi,

$category->products()->paginate(12); // add () after products
tehseen's avatar

thanks both of you guys its works, But now if i use

{{ $categoryProducts->previousPageUrl() }}
{{ $categoryProducts->next() }}

it gives me the below error why ?

Method next does not exist. (View:
Snapey's avatar

There is no next() it is nextPageUrl()

You will also need to append the slug to the URL so that it appears on page 2,3 etc

$category->products()->paginate(12)->appends(['slug'=>$category->slug]);

Please or to participate in this conversation.