Posts Learn Components Snippets Categories Tags Tools 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

1926 views

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

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for How to Loop OR condition in Laravel Eloquent

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Sponsors 👑

+ Add Yours
)