I am trying to save a field from the created
model event but for some reason the stripe_coupon_id
column is never being saved. The created
event does run as I've tested by trying a dd
inside it and it does fire the event but just does not save that column.
class DiscountRate extends Model
{
public $table = "discount_rates";
public $primaryKey = "id";
public $timestamps = true;
public $fillable = [
'id',
'name',
'rate',
'active',
'stripe_coupon_id'
];
public static function boot()
{
parent::boot();
self::created(function ($discountRate) {
$coupon_id = str_slug($discountRate->name);
$discountRate->stripe_coupon_id = $coupon_id;
});
}
}
In my controller I simply call a service function which calls the default Laravel model create function:
public function store(DiscountRateCreateRequest $request)
{
$result = $this->service->create($request->except('_token'));
if ($result) {
return redirect(route('discount_rates.edit', ['id' => $result->id]))->with('message', 'Successfully created');
}
}
discount_rates
table:
The created
event is triggered after your model is created. In this case, you need to to call $discountRate->save()
in the end in order to update the model which you just created.
As alternative, you can use creating
event instead. In this case you don't need to call save()
in the end because the model is not yet saved in your database. A big difference in creating
event is that the model does not have an id yet if you use auto-incrementing which is default behavior.
More info about events you can find here.
you have to set stripe_coupon_id
before creating. So replace static::creating
instead of self::created
in boot
method of DiscountRate
model.