Set a default per page in a query unless the user has selected a per page limit
Hello,
I would like to be able to specify a default number of results per page unless the user has selected a value for this.
The problem is that I don't know how to fetch the results if I use an if/else statement for the "per_page" input element.
Here's what I have so far.
Any help is appreciated.
public function index(Request $request)
{
$query = (new User)->newQuery();
// Search for an user
if ($request->has('search'))
{
$query->where('name', 'like', '%' . $request->input('search') . '%')->orWhere('description', 'like', '%' . $request->input('search') . '%')->orWhere('uuid', 'like', '%' . $request->input('search') . '%');
}
// Order results
if ($request->has('order_by'))
{
$query->orderBy($request->input('order_by') , $request->input('order_direction'));
}
// Set the number of results per page
if ($request->has('per_page'))
{
$query->paginate($request->input('per_page'));
} else {
$query->paginate(20);
}
$users = $query->get();
return view('users.index', compact('users'));
}
paginate() executes the query, so you don't need to get() it. You can also pass a default value to $request->input($field, $default), and if the $field doesn't exist or have a value, it will use the $default.
// Set the number of results per page
$perPage = $request->input('per_page', 20); // if per_page has a value, it will use that. If it doesn't, it will use 20
$users = $query->paginate($perPage);
return view('users.index', compact('users'));