Skip to content
Advertisement

Laravel 5 Eloquent where and or in Clauses

i try to get results from table with multiple where and/or clauses.

My SQL statement is:

SELECT * FROM tbl
WHERE m__Id = 46
AND
t_Id = 2
AND
(Cab = 2 OR Cab = 4)

How i can get this with Laravel Eloquent?

My Code in Laravel is:

$BType = CabRes::where('m_Id', '=', '46')
                        ->where('t_Id', '=', '2')
                        ->where('Cab', '2')
                        ->orWhere('Cab', '=', '4')
                        ->get();

Advertisement

Answer

Using advanced wheres:

CabRes::where('m__Id', 46)
      ->where('t_Id', 2)
      ->where(function($q) {
          $q->where('Cab', 2)
            ->orWhere('Cab', 4);
      })
      ->get();

Or, even better, using whereIn():

CabRes::where('m__Id', 46)
      ->where('t_Id', 2)
      ->whereIn('Cab', $cabIds)
      ->get();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement