2 回答

TA贡献1826条经验 获得超6个赞
你很近。我可能会在您在控制器中实际创建模型之后立即调度一个事件。像这样的东西。
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));
}
}

TA贡献1871条经验 获得超13个赞
我在 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 事件也是一种更好、更清洁的方法。但是事件解决方案的问题是您无法确定模型是否已创建,是时候调用事件还是它仍处于创建状态(而不是创建状态)。
- 2 回答
- 0 关注
- 114 浏览
添加回答
举报