I\'m using the Laravel Eloquent query builder and I have a query where I want a WHERE
clause on multiple conditions. It works, but it\'s not elegant.
E
$variable = array('this' => 1,
'that' => 1
'that' => 1,
'this_too' => 1,
'that_too' => 1,
'this_as_well' => 1,
'that_as_well' => 1,
'this_one_too' => 1,
'that_one_too' => 1,
'this_one_as_well' => 1,
'that_one_as_well' => 1);
foreach ($variable as $key => $value) {
User::where($key, '=', $value);
}
Model::where('column_1','=','value_1')->where('column_2 ','=','value_2')->get();
OR
// If you are looking for equal value then no need to add =
Model::where('column_1','value_1')->where('column_2','value_2')->get();
OR
Model::where(['column_1' => 'value_1','column_2' => 'value_2'])->get();
Query scopes may help you to let your code more readable.
http://laravel.com/docs/eloquent#query-scopes
Updating this answer with some example:
In your model, create scopes methods like this:
public function scopeActive($query)
{
return $query->where('active', '=', 1);
}
public function scopeThat($query)
{
return $query->where('that', '=', 1);
}
Then, you can call this scopes while building your query:
$users = User::active()->that()->get();
Multiple where clauses
$query=DB::table('users')
->whereRaw("users.id BETWEEN 1003 AND 1004")
->whereNotIn('users.id', [1005,1006,1007])
->whereIn('users.id', [1008,1009,1010]);
$query->where(function($query2) use ($value)
{
$query2->where('user_type', 2)
->orWhere('value', $value);
});
if ($user == 'admin'){
$query->where('users.user_name', $user);
}
finally getting the result
$result = $query->get();
You can use subqueries in anonymous function like this:
$results = User::where('this', '=', 1)
->where('that', '=', 1)
->where(function($query) {
/** @var $query Illuminate\Database\Query\Builder */
return $query->where('this_too', 'LIKE', '%fake%')
->orWhere('that_too', '=', 1);
})
->get();
A sample of code.
Firstly :
$matchesLcl=[];
array gets filled here using desired count / loop of conditions, incremently :
$matchesLcl['pos']= $request->pos;
$matchesLcl['operation']= $operation;
//+......+
$matchesLcl['somethingN']= $valueN;
and further with eloquents like this shrink expression :
if (!empty($matchesLcl))
$setLcl= MyModel::select(['a', 'b', 'c', 'd'])
->where($matchesLcl)
->whereBetween('updated_at', array($newStartDate . ' 00:00:00', $newEndDate . ' 23:59:59'));
else
$setLcl= MyModel::select(['a', 'b', 'c', 'd'])
->whereBetween('updated_at', array($newStartDate . ' 00:00:00', $newEndDate . ' 23:59:59'));