Bene
Bene

Reputation: 56

Laravel: Filter through collection by search term

I have the following problem: I want to create an instant-search, where I get immediate results via AJAX as soon as the user starts typing. Instead of performing an extra database-query within six tables for each 'keyup' I wanted to eager-load all the database records and provide them in my view. That way I only need to search if my collection items contain the search term and return these as results. I know I can narrow the collection down with the where()-method, e.g.

$words = $words->where('lemma', 'mysearchterm'); return $words;

The problem is, I don't want to retrieve exact matches, but use wildcards like in standard SQL-Queries (SELECT * FROM nouns WHERE lemma LIKE %$mysearchterm%).

How do I do this? I have been trying for two hours now. Does this even make sense? Or is there no performance-advantage to just querying the DB every single time once the user starts typing? Is there a better way to do this?

Thanks in advance!

Upvotes: 0

Views: 1218

Answers (1)

Bene
Bene

Reputation: 56

Thanks for your answers. I will definitely have a look at Scout. I solved my problem with this code:

$result = $words->filter(function ($value, $key) {

    if (strpos($value->lemma, $mysearchterm) !== false) {
        return $value;
    }
});

Upvotes: 1

Related Questions