Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

marvino's avatar

Calculate Dates in mysql using carbon and laravel

Im new, using carbon with laravel, im building a system that will show an employee will be receiving the salary step increase in every three years and adds to their previous step.

Sample scenario.

  • Juan was hired last April 23, 2003 with salary step of 1. *Every three years the salary step should add up 1. *We will compute the current date to Juan date of hired. As expected manually computation the salary step increase of Juan right now should be 6.(Because we add 1 in every three years).

After that in the system i build there is also a summary of employees who should be receiving their salary step increment this year. It is possible to do? anyone can help.

0 likes
8 replies
bobbybouwmann's avatar

What have you tried so far?

In general you can pass Carbon objects to the query builder of Laravel

$employees = Employee::where('hire_date', Carbon::now())->get();

For between dates you can use the whereBetween helper, also with Carbon

$employees = Employee::whereBetween('hire_date', [Carbon::now(), Carbon::now()->addYear()])->get();

Documentation: https://laravel.com/docs/5.6/queries#where-clauses

kobear's avatar

You can do a raw DB query using MOD() on the original hire date

Assuming EMPLOYEES table that has a datetime field named HIRE_DATE

SELECT * FROM EMPLOYEES
WHERE
MOD(YEAR(NOW())-YEAR(EMPLOYEES.HIRE_DATE),3) = 0
marvino's avatar

bobbybouwmann i tried but there is always time, how to remove it? and i need the format of mm/dd/yyy

marvino's avatar

How can i subtract dates in my database to now ? and how will i solve the problem above. Im being crazy thinking. Every time i tried, i got error. I REALLY NEED HELP HERE.

bobbybouwmann's avatar

You already talk about Carbon in your question! Look at the documentation and you know what to do ;)

marvino's avatar

Can i convert this one to eloquent ? need some help here.

public function get_step($last_date_promotion) { $today = new \DateTime(); $first_day = new \DateTime($last_date_promotion); $diff = $today->diff($first_day); $yeartoadd = 0; if ($diff->y) { if ($diff->y > 3) { $nodecimal = floor(((($diff->y) / 3) * 100) / 100); if ($nodecimal >= ? { return "Step 8"; } else { $yeartoadd = ($nodecimal * 3) + 3; $first_day->add(new \DateInterval('P' . $yeartoadd . 'Y')); return $first_day->format('Y-m-d') . " Step " . ($nodecimal + 1); } } else { $first_day->add(new \DateInterval('P3Y')); return $first_day->format('Y-m-d') . " Step 2"; } } else { $first_day->add(new \DateInterval('P3Y')); return $first_day->format('Y-m-d'); } }

Cronix's avatar

@marvino Please format your code with 3 backticks on their own line, followed by code, followed by 3 more backticks on their own line

```

code...

```

will make

code

Please or to participate in this conversation.