'required|exists:components,id', 'startdate' => 'required|date', 'amount' => 'numeric|required|min:0.01', 'repeats' => 'required|between:0,1', 'repeat_freq' => 'required|in:daily,weekly,monthly,quarterly,half-year,yearly' ]; public static function factory() { $start = new Carbon\Carbon; $start->startOfMonth(); return [ 'component_id' => 'factory|Budget', 'startdate' => $start, 'amount' => '100', 'repeats' => 0, 'repeat_freq' => 'monthly' ]; } public function budget() { return $this->belongsTo('Budget', 'component_id'); } public function component() { return $this->belongsTo('Component', 'component_id'); } public function createRepetition(Carbon $start) { $end = clone $start; // go to end: switch ($this->repeat_freq) { case 'daily': $end->addDay(); break; case 'weekly': $end->addWeek(); break; case 'monthly': $end->addMonth(); break; case 'quarterly': $end->addMonths(3); break; case 'half-year': $end->addMonths(6); break; case 'yearly': $end->addYear(); break; } $end->subDay(); $count = $this->limitrepetitions()->where('startdate', $start->format('Y-m-d'))->where( 'enddate', $start->format('Y-m-d') )->count(); if ($count == 0) { $repetition = new \LimitRepetition(); $repetition->startdate = $start; $repetition->enddate = $end; $repetition->amount = $this->amount; $repetition->limit()->associate($this); try { $repetition->save(); \Log::debug('Created new repetition with id #' . $repetition->id); } catch (QueryException $e) { // do nothing \Log::error('Trying to save new Limitrepetition failed!'); \Log::error($e->getMessage()); } } } public function limitrepetitions() { return $this->hasMany('LimitRepetition'); } public function getDates() { return ['created_at', 'updated_at', 'startdate', 'enddate']; } }