Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Jul 29, 2024

Conversation

gdebrauwer
Copy link
Contributor

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.

@gdebrauwer gdebrauwer changed the title [01.x] Allow setting custom scout builder class [10.x] Allow setting custom scout builder class Jul 26, 2024
@taylorotwell taylorotwell merged commit 0dc8e21 into laravel:10.x Jul 29, 2024
15 checks passed
@francoism90
Copy link

@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. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants