Skip to content

Conversation

colq2
Copy link
Contributor

@colq2 colq2 commented May 13, 2025

This PR adds the possibility to define a newScoutQuery() in models. This method allows you to customize the underlying database query used during a search.

For many applications the database engine is everything you need. In almost every project I had 2-3 models which should be searchable by their relations like "Find orders by customers email".

With this change, you can define the necessary joins:

// Order.php public function newScoutQuery() { return $this->newQuery()->join('customers', 'orders.customer_id', '=', 'customers.id'); } public function toSearchableArray(): array { return [ 'orders.id' => $this->id, 'customers.email' => '', 'customers.name' => '', ]; }

And we can get the results

Order::search('mail@example.com')->get();

If we need the search string we can get that from the scout builder

public function newScoutQuery(\Laravel\Scout\Builder $builder): Builder { // use $builder->query in query return $this->newQuery(); }

Why it matters

It is already somehow possible, but you have to extend the search method. And this does not work with laravel nova, because nova overrides the query callback of the scout builder

// Order.php use Searchable { Searchable::search as parentSearch; } public static function search($query = '', $callback = null): \Laravel\Scout\Builder { return static::parentSearch($query, $callback)->query(function ($query) { $query->join('customers', 'orders.customer_id', '=', 'customers.id') }); }
@taylorotwell taylorotwell merged commit 102fe09 into laravel:10.x May 13, 2025
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants