簡體   English   中英

Laravel - 將變量從 controller 傳遞到 model 或從 model 訪問 controller 中的變量

[英]Laravel - Passing a variable from controller to model or accessing a variable in the controller from the model

我想將controller中的一個變量傳遞給laravel中的model。

在Controller,

$withoutUser = True;

$post->update([
    'status' => 'inactive'
]);

在model,

protected static function boot(): void
{
   parent::boot();
   static::updated(fn (Model $model) =>
        // Need to access the $withoutUser variable from here?
   );
}

在調用 $post->update() 時是否有傳遞 $withoutUser 變量的方法,或者在 model 中調用 static::updated 方法時是否可以訪問 controller 中的 $withoutUser 變量?

謝謝

您可以通過在帖子 model 上創建一個屬性來執行此操作。帖子 class 的完全相同的實例將發送到事件調度程序。 所以你可以這樣寫你的代碼:

class Post extends Model
{
    public bool $updateWithoutUser = false;
    ...
}

然后在您的 controller 中:

$post->updateWithoutUser = true;
$post->update([
    'status' => 'inactive',
]);

在引導 function 中:

protected static function boot(): void
{
    parent::boot();
    static::updated(function (Post $post) {
        if ($post->updateWithoutUser) {
            ...
        }
    });
}

如果您正在排隊監聽器,您應該小心,因為在這種情況下,當監聽器從隊列中運行時,屬性將不會被保留,因為它會從數據庫中獲取帖子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM