Using a model scope:
public function scopeApproved($query)
{
return $query->where('activated_at', '>=', 'deactivated_at' -7 days);
}
I know that this is invalid syntax but thought it might be clear what i am trying to achieve.
'activated_at' and 'deactivated_at' are two fields in the same table i would like to get all instances where they are more then 7 days apart
You can use Laravel scopes to DRY up the code. A scope is just a method which you can use in your model to encapsulate the syntax used to execute a query such as above. Scopes are defined by prefixing the name of a method with scope, as below.
Here following the example of active and inactive status in laravel 7/6 we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command: In this is step we need to create route for active and inactive status layout file in laravel 6
So, there are two way to create disable created_at and updated_at timestamps in laravel 5 application. So first you can simply "$timestamps" equals to false in your model. So you can do it as simple bellow example of Item model.
At that time you need to get/fetch active records from the database tables using the laravel query scopes. Laravel query scopes to save your time to write code again and again.
Shempigon answer is almost correct it only has one issue, you don't wrap the columns name in single quote and also the dates have to be switched, something like this:
public function scopeApproved($query) {
$query->whereRaw("DATEDIFF(deactivated_at, activated_at) >= 7");
}
This is because expects this input: DATEDIFF(endDate, starDate)
, you can read more about DATEDIFF here
I'm not sure there is a proper way to achieve this via Eloquent, though you can use MySQL function DATEDIFF. Try something like :
// in your model
public function scopeApproved($query) {
$query->whereRaw("DATEDIFF('activated_at','deactivated_at') >= 7");
}
This is dependant on the database driver you are using (ie. MySQL, SQLite, SQL server, ...)
EDIT:
Found something else that works (so far) with MySQL :
// in your model
public function scopeApproved($query) {
$query->whereRaw("TO_DAYS(activated_at) - TO_DAYS(deactivated_at) >= 7");
}
TO_DAYS being a build in MySQL function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With