Hi @erron
As suggested before, you could create a Trait with that code inside. You could even call that Trait HasApproval or something like that.
As that Trait will be assigned to a Model, you won't need to fetch it from DB as it will be already done, so you would end up with something like:
<?php
namespace App\Traits;
trait HasApproval
{
public function approve()
{
if($this->cancelled_at != null) {
abort(422);
}
if($this->submitted_at == null) {
abort(422);
}
if($this->approved_at != null) {
abort(422);
}
$this->approved_at = now();
$this->save();
}
}
then at the Models where you want to apply this, you would just do:
<?php
namespace App\Models;
use App\Traits\HasApproval;
class SomeModel extends Model
{
use HasApproval;
// your model code here....
}
So now you can call the approve() method on that Model and it will validate and save or abort with 422 code.
Hope this works for you!