Eloquent query though multiple whereHas

I’m trying to do a query with multiple nested whereHas.

I my DB, I have a table ‘Ad’ that has two type of children; ‘Media’ and ‘time_slot’ both relation are of type ‘hasMany’.

I want to find medias that have a parent Ad who has a time_slot child that fits certain condition. This code has been solved and yet works:

$today = date('Y-m-d H:i:s');
$frm = "some string";
$media = Media::with('ad')
    ->whereHas('ad', function ($q) use ($today) {
        $q->whereHas('time_slot', function ($q2) use ($today) {
            $q2->whereDate('from', <=, $today)->whereDate('to', >=, $today);
    ->where('format', $frm)


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I have refactored and corrected your query:

$frm = "some string";
$media = Media::with('ad')

                    // here we use nested whereHas (relation1.relation2.relation3), 
                    // it's easier to write and read
                ->whereHas('ad.time_slot', function($q){

                    // quotes added around the operator, 
                    // it was probably causing you a syntax error
                    // I also used the now() helper, which will give you the
                    // same result as $today = date('Y-m-d H:i:s')
                    $q->whereDate('from', '<=', now()); 
                    $q->whereDate('to', '>=', now());

                })->where('format', $frm)->inRandomOrder()->firstOrFail();

If the records exist and the relationships correctly configured, it should works.

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x