0

Basically I have installed Laravel Scout with TNT Search, all of the configs are correct and they work, I even got a nice search bar to work with an ajax workflow

But the results from the models are from the entire database collection where as my requirement is only to show results of record of records created by the user who is currently logged in session

The models are related via Eloquent Relationships, they work when access normally via the Auth::user() method but the scout search seems to not be attached to any of the models via the Auth::user() example:

App\CourtCase::search($request->q)->get();

The above works but will return any result in the model (and underlying table) without any regards to if the record is owned or related to the user logged in. My intention is however

Auth::user()->courtcase()->search($request->q)->get();

The error i get is the following

message Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::search()
exception   BadMethodCallException
file    /home/vagrant/code/legistant/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php

Clearly this is because Laravel Scout is not attached or available via the Auth::user() method, I can write code to filter the results after they are returned, but imagine the over head of results before being scope by user, it seems like a waste of all that querying, is there a way to scope to user then use Laravel scout search similar to Auth::user()

Can modify the Auth behavior to attach scout, will it be overwritten using a composer update of Laravel?

1 Answers1

1

So as of 05/05/2019 Laravel Scout does not have a method of scoping queries to Auth user related models, because honestly it is a quite difficult logic to process, especially because the relationships are arbitrary and the keys can be different, a scoping function built internally or externally would have the same computational cost, there is no optimizing here

$results = App\CourtCase::search($request->q)->where('lawyer_id', Auth::id())->get();

This is how I solved it, by attaching a where condition to the search result where it will only show details matching the key, if you are modifying existing code of an application, remember initially scout might show cached results that don't match the filter, which confused me until I refreshed the code

Better code is welcome

  • This is still the correct method in Laravel 9 as per the where clause in the documentation https://laravel.com/docs/9.x/scout#where-clauses – Red Roboto Aug 14 '22 at 01:58