0

I'm building a query for Laravel Scout.

$subchanResults = Subchan::search($query)
    ->when($request->input('incl_nsfw'), function ($query, $incl_nsfw) {
        if ($incl_nsfw == 0) {
            return $query->where('nsfw','!=', 'always');
        }
    }, function ($query) {
        return $query->where('nsfw','!=', 'always');
    })          

->paginate(3);

Laravel Scout only allows basic where clauses, no advanced conditional clauses of any kind, so it's been kind of tricky so far. (Documentation: https://laravel.com/docs/8.x/scout#where-clauses)

My problem is with this line: return $query->where('nsfw','!=', 'always');

It seems that Scout will allow a simple where('column','value') , but if I try to add the 3rd parameter to the where clauses (not equal), it doesn't work.

How can I make this query work? Or do I have to manually trim the results myself after the query?

Felix
  • 2,532
  • 5
  • 37
  • 75

2 Answers2

1

I was hoping to find a workaround within Scout itself, but it seems that conditional clauses are just completely out of the question at the moment for scout. Here is my solution for filtering at the search engine level (Meilisearch) for the same scenario:

$subchanResults = Subchan::search($query, function ($meilisearch, $query, $options) use ($request) {
    if ($incl_nsfw = $request->input('incl_nsfw')) {
        $options['filters'] = 'nsfw != always';
    }   

    return $meilisearch->search($query, $options);
})->get();
Felix
  • 2,532
  • 5
  • 37
  • 75
0

The docs you linked to explain:

Scout allows you to add simple "where" clauses to your search queries. Currently, these clauses only support basic numeric equality checks and are primarily useful for scoping search queries by an owner ID. Since a search index is not a relational database, more advanced "where" clauses are not currently supported

Basically, when you call ::search you are no longer building an Eloquent ORM query; you’re building a Scout query, and the where method for a Scout query only accepts two parameters: a key and a value to match against:

https://github.com/laravel/scout/blob/7a8d5b90761e0c102d357dd9e57d8c2f726ceaa5/src/Builder.php#L103-L110

Martin Bean
  • 38,379
  • 25
  • 128
  • 201