In my Laravel application, I have an API entry point where I collect initial data for my application, for example I get paginated results for posts, tags, users...
I'm using paginate:15 for all records, but for users I want to use paginate:30 because in my request parameters I have something like this:
page=1&paginate=15
Is there a way to change it to 30 inside my controller method
Initial Controller
$users = $this->userService->getUsersPaginated($request); $users = $this->vuePaginate($users);
In my User model:
public function getUsersPaginated($request) { $users = User:: paginate($request['paginate']); return $users; }
P粉1279012792024-03-23 12:20:23
Based on user type, evaluate whether the paging size can be handled on the front end.
Anyway, if you want to handle it on the backend, you can find a condition to set the paging size.
For example:
if ($currentUser->role == 'final-user') // 或类似的条件 $perPage = max (30, $request['paginate']); else $perPage = $request['paginate']; $users = User::paginate($perPage);
I also recommend that you set a minimum and maximum value for pagination to avoid problems with wrong values from the frontend (imagine if you got a value like 1,000,000 or -1)
const DEFAULT_RESULTS_PER_PAGE = 15; const FINAL_USER_RESULTS_PER_PAGE = 30; const MAX_RESULTS_PER_PAGE = 100; /* ... */ public function getUsersPaginated($request) { $perPage = min (max ($request['paginate'] ?: self::DEFAULT_RESULTS_PER_PAGE, 1), self::MAX_RESULTS_PER_PAGE); if (/* condition */) $perPage = max (self::FINAL_USER_RESULTS_PER_PAGE, $perPage); $users = User::paginate($perPage); /* ... */
Also note that the default pager request variable is per_page