Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 502
M Arfan Avatar asked Apr 13 '17 09:04

M Arfan


4 Answers

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

like image 103
Alexey Mezenin Avatar answered Oct 13 '22 01:10

Alexey Mezenin


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();
like image 44
Robert Avatar answered Oct 13 '22 01:10

Robert


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();
like image 45
Anar Bayramov Avatar answered Oct 12 '22 23:10

Anar Bayramov


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();
like image 42
Milad.biniyaz Avatar answered Oct 13 '22 01:10

Milad.biniyaz