Search code examples
laravelobserverslaravel-nova

Laravel Nova – Manually Send Error Alert From Observer Class


I have a Season Resource model with a field named active.

The requirement is to disable deletion for a season with an active status.

I have created an Observer for the season model to watch deleting an event. From this function, I can block the delete in case active is true.

But the issue is with the error message; is there any way to add an error message to session flash from the Observer class?

<?php

public function deleting(Season $season)
{
    if($season->active_season)
    {
        Log::info('Sorry, this season can`t be deleted. 
            There must be at least one active season.');
    }

    return false;
}

Solution

  • I don't know how to flash the error message.

    But since the requirement is to disable deletion for a season with an active status, I'm suggesting to use policy which won't display the delete icon when doesn't match the condition.

    class SeasonPolicy {
        ...
    
        public function delete(User $user, Season $season) {
            if($season->active_season) {
                return false;
            }
            return true;
        }
    }
    

    and register the policy in AuthServiceProvider.

    Note:

    Undefined Policy Methods

    If a policy exists but is missing a method for a particular action, the user will not be allowed to perform that action. So, if you have defined a policy, don't forget to define all of its relevant authorization methods.