简体   繁体   中英

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

I want to pass a variable in the controller to the model in laravel.

In Controller,

$withoutUser = True;

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

In model,

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

Is there a method to pass the $withoutUser variable when calling $post->update() or is it possible to access the $withoutUser variable in the controller when the static::updated method is called in model?

Thanks

You can do this by creating a property on the post model. The exact same instance of the post class is sent to the event dispatcher. So you can write your code something like this:

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

And then in your controller:

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

And in the boot function:

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

Though you should be careful if you are queueing the listener, because in that case the property will not be preserved as it fetches the post from the database when the listener is run from the queue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM