Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Where and OrWhere multiple conditions

Tags:

laravel

I have the following query:

$items = UserItems::join('items','items.id','=','user_items.item_id')
            ->where('user_id','=',$this->id)
            ->where('quantity','>',0)
            ->where('items.type',"stones")
            ->orWhere('items.type',"fish")
            ->get();

My problem is that this query returns the items of ALL users instead of the given user_Id.. It's because the orWhere applies on all of the where's but I need it to apply only on this:

->where('items.type',"stones")
                ->orWhere('items.type',"fish")

How I can fix the query to return only the given $this->id user items?

like image 398
TheUnreal Avatar asked Sep 17 '25 14:09

TheUnreal


1 Answers

Laravel supports Advanced Where Clauses like such:

$items = UserItems::join('items','items.id','=','user_items.item_id')
    ->where('user_id','=',$this->id)
    ->where('quantity','>',0)
    ->where(function($query) {
        $query->where('items.type',"stones")
            ->orWhere('items.type',"fish");
    })
    ->get();

I guess another option (cleaner, easier to read IMO), as opposed to using orWhere, could be to use the whereIn operator like:

$items = UserItems::join('items','items.id','=','user_items.item_id')
    ->where('user_id','=',$this->id)
    ->where('quantity','>',0)
    ->whereIn('items.type', ["stones", "fish"])
    ->get();
like image 86
camelCase Avatar answered Sep 19 '25 06:09

camelCase