使用启动插入数据后如何触发事件? (laravel)

时间:2019-08-21 06:05:10

标签: laravel laravel-5.8

我正在找到一种方法,在雄辩者完成创建后触发事件。

这是我在with transaction.atomic(): do something like subtract stock log stuff in DB so that we can later investigate what went wrong if something goes wrong: # this line of code may reside in a function nested deep raise do more to finalize the order 模型中的代码:

Branch

我想做的是,我想在创建分支后创建一个 history_log 。 但是此代码返回错误:

  

Symfony \ Component \ Debug \ Exception \ FatalThrowableError:参数1传递给        App \ Vehicle :: App {closure}()必须是App \ HistoryLog的实例,        应用程序\车辆给定,在D:\ document \ My Documents \ optodph \ vendor \ laravel \ fr中调用       第347行上的amework \ src \ Illuminate \ Events \ Dispatcher.php

有人可以向我指出该代码有什么问题吗?那么实现这一目标的正确方法是什么?

3 个答案:

答案 0 :(得分:1)

使用Laravel的方式。

创建观察者:

php artisan make:observer BranchObserver --model=Branch

将您的逻辑添加到观察者:

<?php

namespace App\Observers;

use App\Branch;

class BranchObserver
{
    /**
     * Handle the Branch "created" event.
     *
     * @param  \App\Branch  $branch
     * @return void
     */
    public function created(Branch $branch)
    {
        // Add your logic here
    }
}

AppServiceProvider中注册:

<?php

namespace App\Providers;

use App\Branch;
use App\Observers\BranchObserver;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Branch::observe(BranchObserver::class);
    }
}

答案 1 :(得分:0)

$ model是创建的新记录。是App\Vehicle而不是App\HistoryLog的实例。

工作代码可能如下所示:

class Vehicle extends Model
{
    //some code here

    public static function boot() {
        parent::boot();

        self::created(function ($model) { 
            App\HistoryLog::create([...]);
        });
    }
}

答案 2 :(得分:0)

您也可以使用雄辩的旁观者https://laravel.com/docs/5.8/eloquent#observers