Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel using WHERE orWHERE

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();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 ?)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading