Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel model scope activated_at and deactivated_at check if has 7 day difference

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

like image 342
Aryeh Armon Avatar asked Feb 04 '16 09:02

Aryeh Armon


People also ask

What is a scope in Laravel?

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.

How to create active and inactive status layout in Laravel 7/6?

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

How to disable created_at and updated_at timestamps in Laravel 5 application?

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.

How to get/fetch active records from the database tables in Laravel?

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.


2 Answers

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

like image 127
Fabio Antunes Avatar answered Oct 31 '22 04:10

Fabio Antunes


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.

like image 32
shempignon Avatar answered Oct 31 '22 03:10

shempignon