Dumitru
Dumitru

Reputation: 2183

How to paginate ítems inside relationship in Laravel?

I have model Category with relation products:

public function products()
{
    return $this->hasMany(Product::class);
}

In MainController I have code:

$products = Category::with('products')->whereNull('parent_id')->paginate(15);

Method paginate only paginate categories, but How I can paginate products?

Upvotes: 2

Views: 357

Answers (1)

Pourbahrami
Pourbahrami

Reputation: 320

It's not a good idea to use pagination inside another pagination, but if you want to do this, you should create manual pagination for products of each category:

use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Illuminate\Http\Request;

$categories = Category::with('products')->whereNull('parent_id')->paginate(15);
foreach ($categories as $category) {
    $count = $category->products->count(); // total count of products in this category
    $limit = 10; // count of products per page in child pagination
    $page = $request->input('category'.$category->id.'page', 1); // current page of this category's pagination
    $offset = ($page * $limit) - $limit; // offset for array_slice()
    $itemsForCurrentPage = array_slice($category->products->toArray(), $offset, $limit, true);
    $paginator = new Paginator($itemsForCurrentPage, $count, $limit, $page, [
          'path'  => $request->url(),
          'query' => $request->query(),
    ]);
    $paginator->setPageName('category'.$category->id.'page');
    $category->paginator = $paginator;  
}

return view('categories.index', ['categories' => $categories]);

And then in your categories\index.blade.php:

<ul>
    @foreach ($categories as $category)
        <li>
            <h3>{{ $category->title }}</h3>
            @if ($category->paginator)
                <ul>
                    @foreach ($category->paginator->items() as $product)
                        <li>{{ $product['title'] }}</li>
                    @endforeach
                </ul>
                {{ $category->paginator->links() }}
            @endif
        </li>
    @endforeach
</ul>
{{ $categories->links() }}

I hope this helps, but I say it again, it's not a good idea to use pagination inside another pagination.

Upvotes: 1

Related Questions