Skip to content
Advertisement

Laravel query builder inject column value into Carbon query

I’ve got a query that I’m running in my project on a model called Domain, it returns all domains where the status column of a domain matches complete and a date column is before or equal to a specific set of days.

I’ve recently refactored the model columns and have included a new column called domain_alert_period which is an integer column that holds a value in days, I need to somehow target this column and put it in replace of my existing 30 so that the user is able to control the number of days prior to getting an alert.

What am I missing from this to achieve this?

return Domain::where('status', 'complete')
            ->where(function ($sql) {
              $sql->where('domain_expires_on', '>', Carbon::now()->subDays(2)) // 2 days after expiry
                  ->where('domain_expires_on', '<', Carbon::now()->addDays(30)); // 30 days before expiry
            })
            ->get();

Advertisement

Answer

I believe you can use whereRaw() in your clause to use raw DB expressions, If its MySQL you can use DATE_ADD method with your column value for comparision

$sql->where('domain_expires_on', '>', Carbon::now()->subDays(2)) // 2 days after expiry
    ->whereRaw('domain_expires_on < DATE_ADD(NOW(), INTERVAL domain_alert_period DAY)');
    

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement