0

I need query of my model with method (where) and using LIKE to find results;

Its my code:

public function scopeTags($query, $tags)
{
    /*
     * random = [ 'tag1', 'tag2', 'tag3', ...]
     */
    $random = $tags[rand(0, count($tags) - 1)];
    return $query->where('tags', 'LIKE', "%{$random}%");
}

I need something like that:

public function scopeTags($query, $tags)
{
    /*
     * random = [ 'tag1', 'tag2', 'tag3', ...]
     */
    foreach($tags as $tag) {
        $random[] = "%{$tag}%";
    }
    return $query->where('tags', 'LIKE', $random);
}

What's the best way to do it?

1 Answer 1

1

You need to add a extra where function call for each tag:

public function scopeTags($query, $tags)
{
    /*
     * random = [ 'tag1', 'tag2', 'tag3', ...]
     */
    foreach($tags as $tag) {
        $query->where('tags', 'LIKE', "%{$tag}%"); //this will be a AND
        //$query->OrWhere('tags', 'LIKE', "%{$tag}%"); //this will be a OR
    }
    return $query;
}

or if you need to simulate WHERE (tags like '%tag1%' AND tags like'%tag2%' AND ...) AND (something else) with parenthesis:

public function scopeTags($query, $tags)
{
    return $query->where(function($q) use($tags) {
        foreach($tags as $tag) {
            $q->where('tags', 'LIKE', "%{$tag}%"); //this will be a AND
            //$q->OrWhere('tags', 'LIKE', "%{$tag}%"); //this will be a OR
        }
        return $q;
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.