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)


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.