mercredi 16 mai 2018

Laravel Scout with TNT Search

I am using Laravel Scout to replace my search functionality as it was previously a 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();

But I was doing this for multiple Models like: Article, Event etc so the script looked pretty bloated.

I followed the necessary steps in the documentation and set up Scout to use TNT Search using the Laravel package made available by them.

It says in the Laravel documentation that Scout is not so great 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;
}

So, it should only return Models where published = 'open' within my database table, or so I thought.

However, I run the following command:

php artisan scout:import "App\Article"

Then I perform a search and 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 Scout scans the text and returns the user the profile belongs to.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire