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

1.9K

2 years ago

0 comments

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

Alaz

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

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this