Implement filters and pagination using Laravel Eloquent
P粉010967136
P粉010967136 2023-11-12 18:42:35
0
1
640

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 theCustomerControllerfile:

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粉010967136
P粉010967136

reply all (1)
P粉268284930

Your main problem is this line:

$customers = Customer::all();
The

all()method immediately returns allcustomersrecords 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():

$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));
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!