Laravel 5 Eloquent where and or in Clauses

SqlLaravelEloquent

Sql Problem Overview


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();

Sql Solutions


Solution 1 - Sql

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();

Solution 2 - Sql

Also, if you have a variable,

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

Solution 3 - Sql

When we use multiple and (where) condition with last (where + or where) the where condition fails most of the time. for that we can use the nested where function with parameters passing in that.

$feedsql = DB::table('feeds as t1')
                   ->leftjoin('groups as t2', 't1.groups_id', '=', 't2.id')
                    ->where('t2.status', 1)
                    ->whereRaw("t1.published_on <= NOW()") 
                    >whereIn('t1.groupid', $group_ids)
                   ->where(function($q)use ($userid) {
                            $q->where('t2.contact_users_id', $userid)
                            ->orWhere('t1.users_id', $userid);
                     })
                  ->orderBy('t1.published_on', 'desc')->get();

The above query validate all where condition then finally checks where t2.status=1 and (where t2.contact_users_id='$userid' or where t1.users_id='$userid')

Solution 4 - Sql

You can try to use the following code instead:

 $pro= model_name::where('col_name', '=', 'value')->get();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSinisa P.View Question on Stackoverflow
Solution 1 - SqlLimon MonteView Answer on Stackoverflow
Solution 2 - SqlJaber Al NahianView Answer on Stackoverflow
Solution 3 - SqlHemamaliniView Answer on Stackoverflow
Solution 4 - Sqlsouvik gainView Answer on Stackoverflow