-1

I am having some trouble with where/whereOr queries. I want to check if fitting and dimmability are the same. Then the light_color_code could be 2700K or 2800K. This is my current query:

if ($lightColorCode === '2800K') {
    $correspondingLamps = Lamp::where(['fitting' => $fitting, 'dimmability' => $dimmable, 'light_color_code' => $lightColorCode])
        ->orWhere(['fitting' => $fitting, 'dimmability' => $dimmable, 'light_color_code' => '2700K'])
        ->get();
}

But it returns all the Lamps where fitting or dimmability or the light_color_code matches but they should all match. I don't see what is wrong with this query?

Update: As in the comments suggested I looked at: https://laravel.com/docs/5.7/queries#parameter-grouping and I created the following query:

        $lamps = DB::table('lamps')
            ->where('fitting', '=', $fitting)
            ->where('dimmability', '=', $dimmable)
            ->where(function ($query, $lightColorCode) {
                $query->where('light_color_code', '=', $lightColorCode)
                    ->orWhere('light_color_code', '=', '2700K - 827 Zeer warm wit');
            })
            ->get();

But this returns:

Too few arguments to function App\Http\Controllers\CompareController::App\Http\Controllers{closure}(), 1 passed and exactly 2 expected

I guess this is because I pass $lightColorCode as parameter but I need that parameter in my where.

Baspa
  • 1,099
  • 1
  • 18
  • 49
  • use parameter grouping, follow this link https://laravel.com/docs/5.7/queries#parameter-grouping – Sohel0415 Dec 18 '19 at 07:42
  • Does this answer your question? [Laravel 4 Eloquent Query Using WHERE with OR AND OR?](https://stackoverflow.com/questions/16995102/laravel-4-eloquent-query-using-where-with-or-and-or) – Yasin Patel Dec 18 '19 at 09:01

2 Answers2

2

You can pass the necessary variables from the parent scope into the closure with the use keyword.

$correspondingLamps = Lamp::where(['fitting' => $fitting, 'dimmability' => $dimmable])->where(function($query) use ($lightColorCode){
            $query->where(['light_color_code' => $lightColorCode])->orWhere('light_color_code' => '2700K');})->get();

check this for details https://www.php.net/manual/en/functions.anonymous.php

albus_severus
  • 3,626
  • 1
  • 13
  • 25
1

Try this :

$correspondingLamps = Lamp::where(['fitting' => $fitting, 'dimmability' => $dimmable])
                    ->where(function($query) use ($lightColorCode){
                      $query->where(['light_color_code' => $lightColorCode]) // 2800K
                      ->orWhere('light_color_code' => '2700K');
                    })
                    ->get();
Yasin Patel
  • 5,624
  • 8
  • 31
  • 53