2 回答

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個贊
你很近。我可能會在您在控制器中實(shí)際創(chuàng)建模型之后立即調(diào)度一個事件。像這樣的東西。
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貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超13個贊
我在 eloquent 模型類中使用靜態(tài)屬性解決了這個問題:
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
});
}
}
有用!但我不知道它是否會導(dǎo)致應(yīng)用程序中的任何其他不當(dāng)行為。
在某些情況下,使用 laravel 事件也是一種更好、更清潔的方法。但是事件解決方案的問題是您無法確定模型是否已創(chuàng)建,是時候調(diào)用事件還是它仍處于創(chuàng)建狀態(tài)(而不是創(chuàng)建狀態(tài))。
- 2 回答
- 0 關(guān)注
- 101 瀏覽
添加回答
舉報