Home > other >  How to add filter and pagination with Laravel Eloquent
How to add filter and pagination with Laravel Eloquent

Time:07-12

I am trying to create an API that will return all customers record from the database. But this provides pagination and filtering.,

The filtering feature is an optional query parameter. So would not necessary included it inside query parameter.

But i am facing an issues in doing that.

Here is my index methods from CustomerController file:

    public function index(Request $request)
    {
        // Get how many item per page
        $itemPerPage = $request->query('per_page');

        // SQL Query 
        $customers = Customer::all();

        // Filter data
        if (!empty($request->name)) {
            $customers = $customers->where('name', '=', $request->name);
        }

        // Return the result as JSON
        return new CustomerCollection($customers->paginate($itemPerPage));
    }

Screenshot of Postman

Or have any better approach to combine optional filtering feature with pagination?

Thank you.

CodePudding user response:

Your main issue is this line:

$customers = Customer::all();

The all() method immediately returns all customers records as a Collection, which does not have a ->paginate() method: https://laravel.com/docs/9.x/collections#available-methods.

To optionally chain, use the ->query() method, or a ->when() clause:

Using ::query() instead of ::all():

$itemPerPage = $request->query('per_page');

// SQL Query 
$customers = Customer::query();

// Filter data
if (!empty($request->name)) {
    $customers = $customers->where('name', '=', $request->name);
}

// Return the result as JSON
return new CustomerCollection($customers->paginate($itemPerPage));

Using a ->when() clause:

$itemPerPage = $request->query('per_page');

$customers = Customer::when(!empty($request->name), function ($query) use ($request) {
  $query->where('name', '=', $request->name);
});

return new CustomerCollection($customers->paginate($itemPerPage));
  • Related