Reputation: 2712
I want to be able to save a "followup date" for a student when a new student is created. This followup date needs to be 2 weeks in the future.
I have managed to do this in the controller as follows:
public function store(StudentRequest $request)
{
$data = $request->all();
$data['followup'] = Carbon::now()->addWeeks(2);
$student = Student::create($data);
// ....
}
However, this feels like a very long-winded way of doing things. I feel as though there ought to be a way to do it automatically on the Model with less code. I thought about using a Mutator, but that wouldn't work because the 'followup' field isn't actually being set from anywhere.
Upvotes: 0
Views: 84
Reputation: 1332
You can extend the save
function in your model like this:
...
public function save(array $options = []) {
if(!$this->exists){ # only before creating
$this->attributes['followup'] = Carbon::now()->addWeeks(2);
}
return parent::save($options);
}
...
Upvotes: 1