如何将参数传递给 laravel elequent 模型的事件观察者

我在 laravel 中有一个模型,我想在第一次创建模型对象后做一些事情。最简单的方法是在我的模型类中添加一个静态启动方法,如下面的代码:


class modelName extends Model

{

      public static function boot()

      {

         parent::boot();


         self::created(function ($model) {

             //the model created for the first time and saved

             //do something

            //code here

         });

     }

}

到目前为止,一切都很好!问题是: created 方法接受的唯一参数是模型对象本身(根据文档):


这些方法中的每一个都接收模型作为它们唯一的参数。


https://laravel.com/docs/5.5/eloquent#events


创建模型后,我需要更多的参数。我怎样才能做到这一点?


或者在保证模型已经创建的同时,还有其他方法可以做某事吗?


laravel 版本是 5.5。


哔哔one
浏览 116回答 2
2回答

跃然一笑

你很近。我可能会在您在控制器中实际创建模型之后立即调度一个事件。像这样的东西。class WhateverController{    public function create()    {        $model = Whatever::create($request->all());        $anotherModel = Another::findOrFail($request->another_id);        if (!$model) {            // The model was not created.            return response()->json(null, 500);        }        event(new WhateverEvent($model, $anotherModel));    }}

慕桂英4014372

我在 eloquent 模型类中使用静态属性解决了这个问题:class modelName extends Model{  public static $extraArguments;  public function __construct(array $attributes = [],$data = [])  {     parent::__construct($attributes);     self::$extraArguments = $data  ;   public static function boot()  {     parent::boot();     self::created(function ($model) {         //the model created for the first time and saved         //do something        //code here         self::$extraArguments; // is available in here     });   }}有用!但我不知道它是否会导致应用程序中的任何其他不当行为。在某些情况下,使用 laravel 事件也是一种更好、更清洁的方法。但是事件解决方案的问题是您无法确定模型是否已创建,是时候调用事件还是它仍处于创建状态(而不是创建状态)。
打开App,查看更多内容
随时随地看视频慕课网APP