Support the ongoing development of Laravel.io →
Scout Eloquent Testing

Hi everyone, name is Lucas, first post here and I'm learning Laravel and loving it.

I'm working in a Livewire component that searches for users in the database using Laravel/Scout with tnt search driver. I know it is overkill, but just doing it for the sake of learning like a lot of other stuff that I'm doing in the project aiming for a bigger work in the future.

In my livewire component, the render function have this code:

$users = ($this->search ? User::search($this->search)->orderBy($this->orderBy, $this->orderAsc ? "asc" : "desc")->paginate($this->perPage) : User::orderBy($this->orderBy, $this->orderAsc ? "asc" : "desc")->paginate($this->perPage));

It mean that if there is a search value in the input, it will use laravel scout to search the index, order it and paginate, or it will just paginate the results with order by.

I tried to make it shorter this way:

$users = $this->search ? User::search($this->search) : User::query(); $users->orderBy($this->orderBy, $this->orderAsc ? "asc" : "desc")->paginate($this->perPage);

But that generates a BadMethodCallException: Call to undefined method Illuminate\Database\Eloquent\Builder::links()

Looks like I can't chain methods if not in a single call of User::class

I'm really confused, the first code works, this is just for learning if is possible to make it better without repeating the "orderBy" and "paginate" methods

Thank you for your time!

Last updated 3 years ago.

isaacongoma liked this thread

1

Hi Lucas.

You should be able to use the conditional clause on the builder to achieve this.

Your use-case would be something like this (untested):

$users = User::when($this->search, function ($query) {
    $query->search($this->search);
})
    ->orderBy($this->orderBy, $this->orderAsc ? 'ASC' : 'DESC')
    ->paginate($this->perPage);

lucasjose501, mrkalmdn liked this reply

2

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.