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 關注
- 102 瀏覽
添加回答
舉報