Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent orWhere Query

Can someone show me how to write this query in Eloquent?

SELECT * FROM `projects` WHERE `id`='17' OR `id`='19'

I am thinking

Project::where('id','=','17')
        ->orWhere('id','=','19')
        ->get();

Also my variables (17 and 19) in this case are coming from a multi select box, so basically in an array. Any clues on how to cycle through that and add these where/orWhere clauses dynamically?

Thanks.

like image 801
sarovarc Avatar asked Dec 24 '14 06:12

sarovarc


People also ask

How do you use orWhere in laravel eloquent?

Laravel provides orWhere() to use SQL or query. in or where() we just need to pass two arguments one is the column name and will be valued. You can see below syntax on orWhere query in laravel: orWhere(Coulumn_name, Value);

How do you write orWhere in laravel?

Laravel provide orWhere() to use sql or query query. in or where() we just need to pass two argument one is column name and will be value. You can see bellow syntax on orWhere query in laravel: orWhere(Coulumn_name, Value);

IS NOT NULL in laravel eloquent?

Check if not null: whereNotNullSELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .


2 Answers

The best approach for this case is using Laravel's equivalent for SQL's IN().

Project::whereIn('id', [17, 19])->get();

Will be the same as:

SELECT * FROM projects WHERE id IN (17, 19)

This approach is nicer and also more efficient - according to the Mysql Manual, if all values are constants, IN sorts the list and then uses a binary search.

like image 148
HTMHell Avatar answered Oct 16 '22 23:10

HTMHell


You could do in three ways. Assume you've an array in the form

['myselect' => [11, 15, 17, 19], 'otherfield' => 'test', '_token' => 'jahduwlsbw91ihp'] which could be a dump of \Input::all();

  1.    Project::where(function ($query) {
          foreach(\Input::get('myselect') as $select) {
             $query->orWhere('id', '=', $select);
          }
       })->get();
    
  2.    Project::whereIn('id', \Input::get('myselect'))->get();
    
  3.    $sql = \DB::table('projects');
       foreach (\Input::get('myselect') as $select) {
           $sql->orWhere('id', '=', $select);
       }
       $result = $sql->get();
    
like image 27
Damien Pirsy Avatar answered Oct 17 '22 00:10

Damien Pirsy