Home / Snippets / How to Loop OR condition in Laravel Eloquent
How to Loop OR condition in Laravel Eloquent cover

How to Loop OR condition in Laravel Eloquent


2 years ago


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

Ahmad Aziz

Week-end developer currently experimenting with web, mobile, and all things programming.






Support Us

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

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this