Ad

Laravel Using WHERE OrWHERE

- 1 answer

I have a query as below. When i search using the query below, it fetches the products but it shows other products from other airlines even tho i have specified the airline id. When i take out the orWhere("code","LIKE","%{$request->search}%"), it works perfectly fine and it doesn't show the products of other airlines.

I know where the issue is but then i still need the search parameter to be either name or code. How do i fix this ?

 Product::with('airline')
            ->where('airline_id', $request->airline_id)
            ->select('id','name','code')
            ->where("name","LIKE","%{$request->search}%")
            ->orWhere("code","LIKE","%{$request->search}%")
            ->limit(5)
            ->get();
Ad

Answer

Your current query will generate:

WHERE airline_id = ? AND name LIKE ? OR code LIKE ?

The OR will discount any other conditions unless you group them properly. You need to use logical grouping to solve that:

->select('id','name','code')
->where('airline_id', $request->airline_id)
->where(function ($query) use ($request) {
    $query->where("name","LIKE","%{$request->search}%")
          ->orWhere("code","LIKE","%{$request->search}%");
})

This will generate:

WHERE airline_id = ? AND (name LIKE ? OR code LIKE ?)
Ad
source: stackoverflow.com
Ad