-1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I've updated the question and now you should be able to get a better idea about what actually needs to be done. Kindly check the question again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.