Reputation: 1176
Let's say in my employee table I have a column 'hire_date', I want the employee who has the tenure of 1-3 months or simply only 3-month old employees by 'hire_date'.
I tried this:
Employee::whereDate('hire_date', '<=', Carbon::now()->subMonths(3))
->orderBy('hire_date', 'desc')
->get();
But it returns all the employees.
I printed the raw query and it is just going back 3 months from the current date and then fetching the records.
date(`hire_date`) <= 2020-02-22 //whereDate('hire_date', '<=', Carbon::now()->subMonths(3)
What am I doing wrong? Any Idea to achieve this?
Example: Jhon an employee was hired in a company on 01/Feb/2020. So when he completes his 3 months in the company I want to do something by fetching his records.
Upvotes: 2
Views: 420
Reputation: 49403
So for all person hired between the first and the last dayof the month
Employee::whereDate('hire_date', '>=', Carbon::now()->subMonths(3)->firstOfMonth())
->whereDate('hire_date', '<=', Carbon::now()->subMonths(3)->lastOfMonth())
->orderBy('hire_date', 'desc')
->get();
so that
date(`hire_date`) <= '2020-02-1' AND date(`hire_date`) >= '2020-02-29'
Upvotes: 0
Reputation: 816
Problem: Jhon an employee was hired in a company on 01/Feb/2020. So when he completes his 3 months in the company I want to do something by fetching his records.
Solution for your issue is,
$datetime = new DateTime('NOW'); //Current date
$datetime->modify('- 3 months'); //Date before 3 months
$backDate = datetime->format('Y-m-d'); //Format date
$employees = Employee::whereDate('hire_date', $backDate)
->orderBy('hire_date', 'desc')
->get();
Upvotes: 0