Search code examples
phplaravellaravel-5laravel-scout

Laravel Scout with TNTSearch


I am using Laravel Scout to replace my search functionality as it was previously one big SQL LIKE statement like similar to the below.

$users = User::where('username', 'like', '%'.$request->get('q').'%')
    ->orWhere('displayName', 'like', '%'.$request->get('q').'%')
    ->orWhere('email', 'like', '%'.$request->get('q').'%')
    ->orWhere('role', 'like', '%'.$request->get('q').'%')
    ->orWhere('department', 'like', '%'.$request->get('q').'%')
    ->orWhere('location', 'like', '%'.$request->get('q').'%')
    ->orWhere('directDialIn', 'like', '%'.$request->get('q').'%')
    ->orWhere('mobileNumber', 'like', '%'.$request->get('q').'%')
    ->get();

I was doing this for multiple models I have such as Article, Event, etc. and the script ends up bloated. I followed the necessary steps in the documentation and set up Laravel Scout to use TNTSearch using the Laravel package made available by them.

It says in the Laravel documentation that Laravel Scout is not so good at advanced where clauses, so following the documentation a bit further down the page, I did something like this at the top of my Controller.

use Searchable;

public function shouldBeSearchable()
{
    return $this->published === "open";
}

/**
 * Get the indexable data array for the model.
 *
 * @return array
 */
public function toSearchableArray()
{
    $array = $this->toArray();

    // Customize array...

    return $array;
}

It should only return models where published equals 'open' within my database table (or so I thought). However, I run the following command:

php artisan scout:import "App\Article"

Then perform a search, it still returns closed articles. I thought by defining shouldBeSearchable it would prevent this?

Also, is it possible to index relations on a model when performing a Scout search? For instance, if a user has a profile can I use Scout to search the profile related to the user? I want to be able to type text into a box, and have Scout scan the text and return the user the profile belongs to.


Solution

  • I assume you are using teamtnt/laravel-scout-tntsearch-driver? If so, it doesn't yet support Scout's shouldBeSearchable function.

    Here is the relevant issue ticket: https://github.com/teamtnt/laravel-scout-tntsearch-driver/issues/153