dongyin8009 2018-06-19 10:02
浏览 348
已采纳

Laravel 5.6不在`created`模型事件中保存字段

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:

enter image description here

  • 写回答

2条回答 默认 最新

  • duanjue7508 2018-06-19 11:52
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)