I'm trying to create an API that will return all customer records from a database. But this provides paging and filtering functionality. ,
Filtering function is an optional query parameter. So it doesn't have to be included in the query parameters.
But I'm having trouble doing this.
This is the index method in theCustomerController
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)); }
Or is there a better way to combine optional filtering functionality with pagination?
Thanks.
Your main problem is this line:
Theall()
method immediately returns allcustomers
records as aCollection
, which does not have a->paginate( )
method:https://laravel.com/docs/9 .x/collections#available-methods.To select a link, use the
->query()
method or the->when()
clause:Use
::query()
instead of::all()
:Use
->when()
clause: