S M Abrar Jahin
S M Abrar Jahin

Reputation: 14588

Convert SQL to Laravel Query Builder with complex AND OR

I have a query like this-

SELECT * FROM subscribers_lists
  WHERE Country='Germany'
  AND (City='Berlin' OR name LIKE '%Mün%');

I want to convert it to a Laravel query builder's query. So, what I have done is -

DB::table('Customers')
    ->where('subscribers_lists.Country', '=', $user_country)
    ->or_where('subscribers_lists.City', '=', $user_city)
    ->or_where('subscribers_lists.name', 'like', '%' . $searchParameter . '%');

But it is not working perfectly. Any suggestion, please?

Thanks for helping.

Upvotes: 0

Views: 122

Answers (1)

patricus
patricus

Reputation: 62278

You can use a Closure to create the complex part.

DB::table('subscribers_lists')
    ->where('subscribers_lists.Country', '=', $user_country)
    ->where(function($query) use ($user_city, $searchParameter) {
        $query->where('subscribers_lists.City', '=', $user_city)
              ->orWhere('subscribers_lists.name', 'like', '%' . $searchParameter . '%');
    });

You can read more about advanced queries in the documentation here

Upvotes: 1

Related Questions