Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pasha's avatar
Level 2

Using whereRaw condition on laravel eager loading with query builder

We want's to need those complain, which lifetime(created_at - now()) is grater then a complain lifetime(the lifetime amount stored on complain_type table) by eloquent relationship.

####01.complain table:

|id | complain_preset_id | created_at |

####02. Complain Preset Table:

|id | type_id | created_at |

####03. complain type table

|id | lifetime |

the relation between complain->preset is:

public function preset()
{
    return $this->belongsTo(ComplainPreset::class, 'complain_preset_id');
}

the relation between preset->complain is:

public function complains()
{
    return $this->hasMany(Complain::class, 'complain_id');
}

AND preset->complain_type:

public function complainType()
{
    return $this->belongsTo(ComplainType::class, 'type_id');
}

complain_type->preset:

public function presets()
{
    return $this->hasMany(ComplainPreset::class);
}

Their is no direct relationship between complain to complain_type.

Here is our solution eloquent query. but that query doesn't work.

The relation is complain->preset->complain_type

Complain::with(['preset' => function ($q) {
    $q->with(['complainType' => function($q2) {
        $q2->whereRaw('SUBTIME(NOW(), lifetime) > complains.created_at');
    }]);
}])->whereDate('created_at', '=' , Carbon::today());

In line 3, this query didn't get complains.created_at, because this line refer to complain_type table. On line 3 we need to access complains.created_at.

Is their any eloquent way ?

0 likes
0 replies

Please or to participate in this conversation.