Retrieve results only where ALL keywords match Laravel

59
May 25, 2022, at 6:50 PM

I am trying to pull users based on their tags where ALL keywords match.

Take this working code:

$search_terms = array('keyword 1', 'keyword 2', 'keyword 3', 'keyword 4');
$search_results = User::where('user_type_id', 1)
    ->where('approved', 1)
    ->whereHas('tags', function ($q) use($search_terms) {
        $q->whereIn('name', $search_terms);
    })->get();

At the minute I am using whereIn() to do this, but it will pull users even if they have 1 match out of all the inputted keywords. So if we have keyword 1, keyword 2, keyword 3, keyword 4. The query should only pull results where ALL the keywords are matched in the tags table for a given user.

Answer 1

I think this will work, could you please check

$search_terms = array('keyword 1', 'keyword 2', 'keyword 3', 'keyword 4');
$search_results = User::where('user_type_id', 1)
    ->where('approved', 1)
    ->whereHas("tags", function($q) use ($search_terms) {
        $q->whereIn("name", $search_terms);
        }, "=", count($search_terms));
    ->get();
Rent Charter Buses Company
READ ALSO
Getting an PHP enum from dynamic name

Getting an PHP enum from dynamic name

I´m trying to create an php 81 enum from a dynamic name

48
PHP categories showing only one item

PHP categories showing only one item

I'm trying to create a categories list, where user will be able to choose item with certain category, but as soon as I'm opening any of the categories, where "soon = '2'", there is only one item coming upEverything else works

137
PHP can you convert unicode from within a string

PHP can you convert unicode from within a string

I have a php string with the following

98
Invisible Character Unicode

Invisible Character Unicode

Does anyone know if there is any invisible character other than the space? like a website using (Example: This Invisible Character)Is it possible to programmatically add some such characters that are not shown by any editor, i'm trying by unicode but when ever i paste it so it takes same unicode...

81