jesse_orange_newable
1 month ago

Using Laravel Scout or an SQL LIKE operator

Posted 1 month ago by jesse_orange_newable

In one of my projects we have Articles and Events (singular) and I wanted the ability to search through them with a search bar.

Laravel Scout was great for this as I could literally do the following:


/**
    * Perform a search using what was typed into the search bar
    * Uses Laravel Scout for full text indexing.
    *
    * @param  Request $request
    * @return void
    */
public function search(Request $request)
{
    // Do some validation
    $validated_data = $request->validate([
        'q' => 'nullable|string|max:255',
    ]);

    // Get what was searched for
    $query_string = $validated_data['q'];

    $articles = Article::search($query_string)
        ->where('status', 'published')
        ->orderBy('created_at', 'desc')
        ->get();

    $events = Event::search($query_string)
        ->where('published', 'published')
        ->orderBy('start_datetime', 'desc')
        ->get();
    }

This worked fine.

One day users want tagging so I use https://cartalyst.com/manual/tags/11.x to handle the many-to-many aspects of this request.

So, users now want to be able to search and if it returns nothing, it should instead compare the search term to any available tag.

I've been reading up and I don't think scout would be a good choice at this point because essentially I want to use a bunch or orWhere to do the following:

  1. Search through each column of the model and try to match the string
  2. If we don't find anything, search through the tags

$articles = Article::search($query_string)
    ->where('status', 'published')
    ->orderBy('created_at', 'desc')
    ->get();

if(!$articles){
    $articles = Article::whereHas('tags', function($query){
        $query->where('name', 'like', '%' . $query_string . '%');
    })
}

Is there a better, more efficient way to do this?

Please sign in or create an account to participate in this conversation.