Posts Learn Components new Snippets new Categories Tags About

How to Loop OR condition in Laravel Eloquent

Learn how to loop the OR condition using Laravel Eloquent to conditionally filter many columns with ease

Created on Oct 04, 2021


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.

$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
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.

$query = Post::where('user_id', 1)
    ->where('first', 'a')
    ->orWhere('second', 'b')
    // more conditions here
    ->orwhere('third', 'c');

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻