laravel / scout

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

[11.x] Allow setting custom scout builder class #851

Closed gdebrauwer closed 4 months ago

gdebrauwer commented 4 months 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.