The slow performance of the pagination can be improved by optimizing the query and using proper indexing. Here are a few suggestions to improve the performance:
-
Indexing: Make sure that the columns used in the WHERE clause (
lastname,$request->search) are indexed in the database. This will significantly speed up the search queries. -
Select only required columns: Instead of selecting all columns (
*), specify only the columns that are needed for the pagination. This will reduce the amount of data fetched from the database and improve performance. -
Use eager loading: If the
Accountmodel has any relationships with other models (e.g., orders), consider using eager loading to fetch the related data in a more efficient way. This can help reduce the number of queries executed. -
Use
paginate()instead offastPaginate(): ThefastPaginate()method may not always provide the best performance. Try using the built-inpaginate()method provided by Laravel and see if it improves the performance.
Here's an updated version of the code with the suggested improvements:
$accounts = Account::on('mysql_unbuffered')
->select('id', 'firstname', 'lastname', 'active')
->when($request->q, function ($query, $term) {
$query->where('lastname', 'LIKE', '%' . $term . '%');
})
->when($request->search && count($request->search) > 0, function ($query) use ($request) {
foreach ($request->search as $s) {
$query->orWhere($s, 'LIKE', '%' . $request->q . '%');
}
})
->with('orders') // Replace 'orders' with the actual relationship name
->paginate(config('pagination.pageListSize'));
// Access the orders for each account
foreach ($accounts as $account) {
$orders = $account->orders;
// Do something with the orders
}
Make sure to replace 'orders' in the with('orders') method with the actual relationship name between the Account and Order models.
Remember to also check the database indexes and optimize them accordingly.