I want to add value to specific column for all rows in a table every month.
Users Table:
id | leave_alloc | leave_earn |
---|---|---|
1 | 20 | 0 |
2 | 20 | 1.5 |
3 | 20 | -3 |
4 | 20 | 4 |
Controller:
public function earned_leave(){
$user = User::where('leave_alloc', '!=', null)->get();
foreach($user as $row){
$leave_alloc = $row->leave_alloc;
$earned_leave = $leave_alloc / 12;
$row->leave_earn = $earned_leave;
$row->save();
}
}
Here $earned_leave
will be the result of $leave_alloc
divided by 12
. So, on the first day of every month, I want to add the earned leave amount to the leave_earn
column of all users. This column can hold a negative value and decimal value.
How can I make this automation?
CodePudding user response:
Laravel support task scheduling. For your task you may use ->monthlyOn(4, '15:00');
In most simple realization it looks like
$schedule->call(function () {
$user = User::where('leave_alloc', '!=', null)->get();
foreach($user as $row){
$earned_leave = $row->leave_alloc / 12;
$row->leave_earn = $earned_leave;
$row->save();
}
})->monthlyOn(1, '12:00');
Don't forget to add Cron entry