sarovarc
sarovarc

Reputation: 407

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.

Upvotes: 13

Views: 71090

Answers (5)

Lajos Arpad
Lajos Arpad

Reputation: 77045

The other answers correctly pointed out that Project::whereIn('id', \Input::get('myselect'))->get(); and Project::whereIn('id', [17, 19])->get();

are proper solutions, however, sometimes your criterias are not necessarily related to the same field and you will need to add them as orWhere. For such scenarios, you can do as follows:

function orWhere($query, $criterias) {
    for ($index = 0; $index < count($criterias); $index++) {
        $func = ($index === 0) ? "where" : "orWhere";
        $query = $query->{$func}(...$criterias[$index]);
    }
    return;
}

and then you can do as follows:

$query = orWhere($query, [
    [
        ['id', '=', '19'],
        ['name', '=', 'John']
    ]
]);

Upvotes: 0

Md. Saifur Rahman
Md. Saifur Rahman

Reputation: 404

public function getSearchProducts($searchInput)
    {
        $products = Cache::rememberForever('getSearchProductsWithDiscountCalculationproducts',  function () {
            return DB::table('products_view')->get();
        });

        $searchProducts = $products->filter(function ($item) use($searchInput)  {
            return preg_match('/'.$searchInput.'/i', $item->productName) || preg_match('/'.$searchInput.'/i', $item->searchTags) ;
        });

         $response = ["status" => "Success", "data" => $searchProducts ];
        return response(json_encode($response), 200, ["Content-Type" => "application/json"]);
    }

use filter functionality for any customize situations.

Upvotes: 1

HTMHell
HTMHell

Reputation: 6016

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.

Upvotes: 18

kdlcruz
kdlcruz

Reputation: 1388

In laravel 5 you could do it this way.

$projects = Projects::query();

foreach ($selects as $select) {
    $projects->orWhere('id', '=', $select);
}

$result = $projects->get();    

This is very useful specially if you have custom methods on your Projects model and you need to query from variable. You cannot pass $selects inside the orWhere method.

Upvotes: 4

Damien Pirsy
Damien Pirsy

Reputation: 25445

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

Upvotes: 24

Related Questions