laravel / scout

Laravel Scout provides a driver based solution to searching your Eloquent models.
https://laravel.com/docs/scout
MIT License
1.54k stars 327 forks source link

[10.x] Allow setting custom scout builder class #852

Closed gdebrauwer closed 1 month ago

gdebrauwer commented 1 month ago

If you want to create a dedicated scout builder class for a model, you currently have to override the static search() method.

// Before

class Company extends Model
{
    use Searchable;

    public static function search($query = '', $callback = null)
    {
        return app(CompanyScoutBuilder::class, [
            'model' => new static,
            'query' => $query,
            'callback' => $callback,
            'softDelete' => static::usesSoftDelete() && config('scout.soft_delete', false),
        ]);
    }
}

This PR fixes that so you only have to define a static property on your model

// After

class Company extends Model
{
    use Searchable;

    protected static string $scoutBuilder = CompanyScoutBuilder::class;
}
class CompanyScoutBuilder extends \Laravel\Scout\Builder
{
    public function withinRadius() : self
   {
        // Some complex filter that you want to use in multiple scout searches.
        // Creating a method in a custom scout builder class makes this easy.
        return $this->where(...);
   }
}

This is similar to the static $builder and $collectionClass properties on a model. Those properties respectively allow you to set a custom Eloquent Builder class and an Eloquent Collection class.

francoism90 commented 1 month ago

@gdebrauwer Would it be okay to also add a method?

I use something like this to extend the query builder:

public function newEloquentBuilder($query): UserQueryBuilder
{
    return new UserQueryBuilder($query);
}

To something like this:

public function newScoutBuilder($scout): UserScoutBuilder
{
    return new UserScoutBuilder($scout);
}

Or is this actually discourage?

This helps a lot, because now I'm using taps to extend Scout. :)