baig772 baig772 - 2 months ago 7
MySQL Question

Laravel - How to do nested where with And and OR in same query

I have a following query

$updates = FolderLocker::where('created_at', 'like', $date . '%')
->orWhere('date_forwarded', 'like', $date . '%')
->orWhere('date_locked', 'like', $date . '%')
->orWhere('date_completed', 'like', $date . '%')
->whereIn('videographer_id', $videographerArray)
->orderBy('client_id', 'DESC')

->toSql();


It generates

select * from `folder_lockers` where `created_at` like ? or `date_forwarded` like ? or `date_locked` like ? or `date_completed` like ? and `videographer_id` in (?, ?, ?, ?, ?, ?, ?) order by `client_id` desc


How can I make the
whereIn
clause the main one and then all the
OR
clauses in another AND?

Answer

You can group your wheres in a closure, like this:

$updates = FolderLocker::whereIn('videographer_id', $videographerArray)
               ->where(function ($query) use ($date) {
                   $query->where('created_at', 'like', $date . '%')
                       ->orWhere('date_forwarded', 'like', $date . '%')
                       ->orWhere('date_locked', 'like', $date . '%')
                       ->orWhere('date_completed', 'like', $date . '%');
               })                
               ->orderBy('client_id', 'DESC');