PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 16, 2022

[FIXED] How to create Eloquent query from request with OR and AND conditions in Laravel 6?

 November 16, 2022     eloquent, laravel, laravel-6     No comments   

Issue

I send in this JSON object to the API endpoint:

[
    {
        "name": "John",
        "city": "Berlin",
    },
    {
        "name": "Jack",
        "country": "USA",
    }
]

I want to create this SQL query:

SELECT * FROM users WHERE
  (`name` = "John" AND `city` = "Berlin")
  OR
  (`name` = "Jack" AND `country` = "USA");

I have a User model to handle users.

What is the most simpliest way to create this SQL query with Laravel Eloquent query builder?


Solution

return User::orWhere(function (Builder $query) {
        return $query->where('name', 'John')->where('city', 'Berlin');
    })->orWhere(function (Builder $query) {
        return $query->where('name', 'Jack')->where('country', 'USA');
    })->get();

(edit) If you want to send parameter(s);

$city = 'Berlin';
$country = 'USA';

return User::orWhere(function (Builder $query) use ($city) {
        return $query->where('name', 'John')->where('city', $city);
    })->orWhere(function (Builder $query) use ($country) {
        return $query->where('name', 'Jack')->where('country', $country);
    })->get();

If you want to generate it dynamically;

public function index()
{
    $parameters = [
        [
            'name' => 'John',
            'city' => 'Berlin',
        ],
        [
            'name' => 'Jack',
            'country' => 'USA',
        ]
    ];

    $query = User::query();

    foreach ($parameters as $item) {
        $query->orWhere(function (Builder $query) use ($item) {
            foreach ($item as $key => $value) {
                $query->where($key, $value);
            }
        });
    }

    return $query->get();
}


Answered By - Ersoy
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing