Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cosminc's avatar

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'));
}
0 likes
2 replies
Cronix's avatar
Cronix
Best Answer
Level 67

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'));
1 like
cosminc's avatar

Ah, so simple! :) Didn't thought of that. Thanks.

Please or to participate in this conversation.