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

n212's avatar
Level 2

Pagination question with query()

Hi, I have a simple method that handles pagination with search. I was wondering why using Guild::query() does not with pagination. Using this method below gives me the error of Call to undefined method links(). However, not using query() and handling it separately works fine.

What's the reason behind this? Is there a better way to write this method below? Thanks for any advice.

    public function showHomePage(Request $request)
    {

        $search = "";
        $guilds = Guild::query();

        if ($request->has('search')) {
            $search = $request->get('search');
            $guilds->whereLike('guild_id', $request->get('search'));
        }

        $guilds->paginate(1);

        return view('index', compact('guilds', 'search'));
    }

Working method

    public function showHomePage(Request $request)
    {

        $search = "";

        if ($request->has('search')) {
            $search = $request->get('search');
            $guilds = Guild::whereLike('guild_id', $request->get('search'))->paginate(1);
        } else {
            $guilds = Guild::paginate(1);
        }

        return view('index', compact('guilds', 'search'));
    }
0 likes
4 replies
jlrdw's avatar

I don't thin the first does anything:

$guilds = Guild::query();

I don't understand sending the two separate things, but I don't know your data.

1 like
Snapey's avatar

where does whereLike come from?

1 like
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

That can be simplified alot

$search = $request->input('search', '');
$guilds = Guild::query()
    ->when($search, function($query, $search) {
         $query->whereLike('guild_id', $search);
   })->paginate(1);

return view('index', compact('guilds', 'search'));
1 like

Please or to participate in this conversation.