John Davidson

php - Laravel query builder inject column value into Carbon query

0 comments
Message:


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();


My Answer:
> You can achieve this by injecting the value of the `domain_alert_period` column into the Carbon query. Here's how you can modify your query to achieve this:

php
use Carbon\Carbon;

$domains = Domain::where('status', 'complete')
->whereDate('date_column', '<=', Carbon::now()->subDays(DB::raw('domain_alert_period')))
->get();


In this modified query, we are using the `subDays` method of Carbon to subtract the number of days specified in the `domain_alert_period` column from the current date. This will dynamically adjust the number of days based on the value stored in the `domain_alert_period` column for each domain.

Make sure to replace `date_column` with the actual name of your date column in the `whereDate` method.

Rate this post

5 of 5 based on 3138 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us