Home > Mobile >  query laravel not working if pass variable in Where NOT IN
query laravel not working if pass variable in Where NOT IN

Time:04-05

I'm trying to filter items from a database table what I do is get the ids that I want to exclude and then through -> whereNotIn in laravel, I pass the ids

$idcontracts=array();
$idbike=array();
$biciCorretta = array();

$findcontract=Contract::whereRaw('? between data_inizio and data_fine', [$datainizio])->whereRaw('? between data_inizio and data_fine', [$datafine])->get();
        foreach ($findcontract as $key) {
            if (!in_array($key->id,$idcontracts)) {
                array_push($idcontracts,$key->id);
            }
        }
        
        foreach ($idcontracts as $idcontract) {
            $bike_contracts=DB::table('bike_contract')->where('contract_id',$idcontract)->get();
            foreach ($bike_contracts as $bike_contract) {
                if (!in_array($bike_contract->bike_id,$idbike)) {
                    array_push($idbike,$bike_contract->bike_id);
                }
            }
            
            
        }
        
        $notid=implode("', '",$idbike);

up to this point I have no problem. the result of "implode" gives me the ids I want to remove

this is the result of $idbike and $notid:

enter image description here

this is the query I write to exclude the ids found:

$bikes = Bike::with('category')->whereNotIn('id', [$notid])->orderBy('category_id')->get();

the problem is that it doesn't exclude me the ids passed with $notid

but if I manually pass the ids, it removes them instead:

$bikes = Bike::with('category')->whereNotIn('id', [40,41,34,36,39])->orderBy('category_id')->get();

am I doing something wrong?

CodePudding user response:

You shouldn't implode $notid, that makes it a string and Laravels whereNotIn() already does that for you.

->whereNotIn('id', $idbike)

And remove the $notid parameter, as it is not needed.

CodePudding user response:

implode will return in string, and because of that it will not work correctly, you should pass it as array instead.

CodePudding user response:

If you print data

$idbike =[40,41,34,36,39];

print_r($idbike);

Output will be Array

Array
(
    [0] => 40
    [1] => 41
    [2] => 34
    [3] => 36
    [4] => 39
)

and if you print below code

$notid=[implode(",",$idbike)];
print_r($notid);

The output will be

Array
(
    [0] => 40,41,34,36,39
)

So your query become

->whereNotIn('id', ["40,41,34,36,39"])

so laravel searching for id of "40,41,34,36,39". so its not returning result

So you can pass array directly to wherenotin

->whereNotIn('id', $idbike)
  • Related