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 the 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)); }
Or is there a better way to combine optional filtering functionality with pagination?
Thanks.
P粉2682849302023-11-13 10:57:10
Your main problem 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 select a link, use the ->query()
method or the ->when()
clause:
Use ::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));
Use ->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));