M Arfan
M Arfan

Reputation: 4575

How to use multiple OR,AND condition in Laravel queries

I need help for query in laravel

My Custom Query: (Return Correct Result)

Select * FROM events WHERE status = 0 AND (type="public" or type = "private")

how to write this query in Laravel.

Event::where('status' , 0)->where("type" , "private")->orWhere('type' , "public")->get();

But it's returning all public events that status is not 0 as well.

I am using Laravel 5.4

Upvotes: 21

Views: 67605

Answers (5)

Muhammad Azeem
Muhammad Azeem

Reputation: 1

  $filter = [];
  $filter[] = "type="public" or type = "private"";
$filter[] = "status = 0";
$event = Event::whereRaw(implode(' AND ',$filter))->get();

You can store all condition in filter array and then apply to query

Upvotes: 0

Milad.biniyaz
Milad.biniyaz

Reputation: 516

Try this. It works for me.

$rand_word=Session::get('rand_word');
$questions =DB::table('questions')
    ->where('word_id',$rand_word)
    ->where('lesson_id',$lesson_id)
    ->whereIn('type', ['sel_voice', 'listening'])
    ->get();

Upvotes: 1

Robert
Robert

Reputation: 5963

In your case you can just rewrite the query...

select * FROM `events` WHERE `status` = 0 AND `type` IN ("public", "private");

And with Eloquent:

$events = Event::where('status', 0)
    ->whereIn('type', ['public', 'private'])
    ->get();

When you want to have a grouped OR/AND, use a closure:

$events = Event::where('status', 0)
    ->where(function($query) {
        $query->where('type', 'public')
            ->orWhere('type', 'private');
    })->get();

Upvotes: 9

Anar Bayramov
Anar Bayramov

Reputation: 11584

Use this

$event = Event::where('status' , 0);

$event = $event->where("type" , "private")->orWhere('type' , "public")->get();

or this

Event::where('status' , 0)
     ->where(function($result) {
         $result->where("type" , "private")
           ->orWhere('type' , "public");
     })
     ->get();

Upvotes: 4

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Pass closure into the where():

Event::where('status' , 0)
     ->where(function($q) {
         $q->where('type', 'private')
           ->orWhere('type', 'public');
     })
     ->get();

https://laravel.com/docs/5.4/queries#parameter-grouping

Upvotes: 36

Related Questions