To loop the OR condition in Laravel Eloquent you can call the WHERE condition and passing a closure (anonymous function) to the method. By doing so you can execute your loop within the function which then will continue chaining the OR conditions.
<?php
$attributes = ['first'=>'a', 'second'=>'b', 'third' => 'c'];
$query = Post::where('user_id', 1)
->where(function ($query) use ($attributes) {
foreach ($attributes as $key=>value)
{
// you can use orWhere the first time, doesn't need to be ->where
$query->orWhere($key,$value);
}
});
If you are writing the code above manually then you may need to call the OR condition one at a time in which if the column is more than 20 or maybe it's a dynamic column, then it would be hard to manage.
<?php
$query = Post::where('user_id', 1)
->where('first', 'a')
->orWhere('second', 'b')
// more conditions here
->orwhere('third', 'c');
Leave a reply