Search code examples
phplaraveleloquentwhere-clause

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, in this case, my variables (17 and 19) come 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.


Solution

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