Have you looked into Task Scheduling with Laravel? You shouldn't have to calculate any of those times.
Recurring Events With Task
Hi All
I have created a form that allows the user to create a task with a recurring event i.e weekly, monthly etc, however i'm having a bit of trouble in submitting on the events side when trying to create the recurring event,
I have a tasks table that hasMany('App\Event') and an events table that belongsTo('App\Task').
Upon submission the task submits but then falls over at the events part with an error of undefined index times.
Ultimately I dont think this is the best way of doing things as it doesn't account for any leap years and i havent figured out how to add the number of days on from the event (i.e if its weekly add 7 days). If someone could advise a better way to do this it would be much appreciated.
//TaskController
....
$newTask = \App\Task::create($form_data);
$recurrences = [
'daily' => [
'times' => 365,
],
'weekly' => [
'times' => 52,
],
'monthly' => [
'times' => 12,
]
];
$event = array(
'task_id' => $newTask->id,
'customer_id' => $request->customer_id,
'start_time' => $request->start,
'end_time' => $request->end,
'recurrence' => $request->recurrence,
);
for($i = 0; $i < $recurrences['times']; $i++)
{
\App\Event::create($event);
}
Thank you in advance.
and thats what the code I posted shows.
You call a function that is named the same as the recurrence. That function creates a new task with the $at date set. It controls the number of iterations and the amount the date should be moved on at each iteration.
The createEvent function needs changing now to createTask and use the Task model, but you should be able to manage that?
$recurrence = strtolower($request->recurrence);
function_exists($this->recurrence)
? $this->$recurrence($newTask)
: return;
$recurrence is the lowercase form of the recurrence field from the form
If there is a function with the same name , ie 'monthly' then call it
The monthly function
private function monthly($newTask)
{
$at = now();
foreach (range(1, 12) as $x) {
$at->addMonth();
$this->createEvent($at, $newTask);
}
}
starts with todays date (you can change this if the user is saying the start date) then does 12 iterations
In each iteration it adds a month and then creates the Event (now needs to be changed to task)
Exactly the same principle for days and weeks but with different number of iterations and the date is moved along by a different amount.
Please or to participate in this conversation.