Recents in Beach

Pagination - 4-Layer

 তোমার Controller একদম ঠিক আছে 👍

Pagination Controller-এ add করা যাবে না — 4-Layer rule অনুযায়ী এটা Service → Repository layer এ করতে হবে।

এখন শুধু getAllProducts() chain ঠিক করলে pagination auto কাজ করবে।


Step-by-Step Pagination Add (4-Layer অনুযায়ী)


1️⃣ Controller (No Change ❌)

তুমি যেটা লিখেছো সেটাই থাকবে

public function index()
{
    $products = $this->productService->getAllProducts();
    return view('admin.product.index', compact('products'));
}

2️⃣ Service Layer (এখানে limit decide হবে)

app/Services/ProductService.php

public function getAllProducts()
{
    return $this->productRepository->paginateProducts(5); // প্রতি page 5 ta
}

👉 Business rule: admin প্রতি page এ 5টা product দেখবে


3️⃣ Repository Layer (Main Fix 🔥)

app/Repositories/ProductRepository.php

namespace App\Repositories;

use App\Models\Product;

class ProductRepository
{
    public function paginateProducts($limit = 10)
    {
        return Product::latest()->paginate($limit);
    }

    public function findById($id)
    {
        return Product::findOrFail($id);
    }

    public function create($data)
    {
        return Product::create($data);
    }

    public function update($id, $data)
    {
        $product = $this->findById($id);
        $product->update($data);
        return $product;
    }

    public function delete($id)
    {
        $product = $this->findById($id);
        return $product->delete();
    }
}

⚠️ খুব গুরুত্বপূর্ণ
আগে যদি all() বা get() থাকত তাহলে error আসবে:

Collection::links does not exist


4️⃣ Blade View

resources/views/admin/product/index.blade.php

<table class="table table-bordered">
    <thead>
    <tr>
        <th>#</th>
        <th>Name</th>
        <th>Price</th>
        <th>Stock</th>
    </tr>
    </thead>

    <tbody>
    @foreach($products as $product)
        <tr>
            <td>{{ $products->firstItem() + $loop->index }}</td>
            <td>{{ $product->name }}</td>
            <td>{{ $product->price }}</td>
            <td>{{ $product->stock }}</td>
        </tr>
    @endforeach
    </tbody>
</table>

<div class="d-flex justify-content-center mt-4">
    {{ $products->links() }}
</div>

5️⃣ Bootstrap Pagination Style Enable

app/Providers/AppServiceProvider.php

use Illuminate\Pagination\Paginator;

public function boot(): void
{
    Paginator::useBootstrapFive();
}

✔️ Final Result

এখন কাজ করবে:

http://127.0.0.1:8000/products?page=1
http://127.0.0.1:8000/products?page=2
http://127.0.0.1:8000/products?page=3

কেন আগে error আসছিল?

তুমি করেছিলেLaravel return করেছিলResult
Product::all()Collection❌ links() নাই
Product::get()Collection
Product::paginate()Paginator

চাও next step এ pagination এর সাথে search + filter + status toggle (AJAX) বানাই?
এটা দিলে তোমার admin panel fully professional হয়ে যাবে 😄

Post a Comment

0 Comments