Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MB's avatar
Level 2

Laravel nova, throw exception in Observer

Hi,

How can I throw exception in an Observer, so the error will show in Nova? This works, but no errors/exception is thrown:

    public function deleting(Wormgear $wormgear)
    {

        # Do not delete ordered products
        if(Orderable::select('id')->where('orderable_id', $wormgear->id)->exists()) {
            
            # stop delete
            return false;
            
        }
        
    }

I have tried to throw an exception, but no error is displayed inside Nova.

use Illuminate\Validation\ValidationException;

throw ValidationException::withMessages([
   'message' => 'not possible to delete ordered products'
]);
0 likes
5 replies
leodesign's avatar
Level 1
  • assume model name is "Mmm"
  • and you have a nova resource name “mmms” with the following fields

public function fields(Request $request) { return [ ID::make()->sortable(),

        Text::make('Name', 'name')->sortable()->rules('required') ,
    ];
}

1- make observer for the “Mmm” model

php artisan make:observer MmmObserver --model=Mmm

2- attach Observer to model

In: App/Providers/AppServiceProvider.php

/** * Bootstrap any application services. * * @return void */ public function boot() { \App\Mmm::observe(\App\Observers\MmmObserver::class); }

3- throw an exception in your model Exception

In App/Observers/MmmObserver.php

public function creating(Mmm $mmm) { throw \Illuminate\Validation\ValidationException::withMessages([ 'name' => ['Errror Message 1'], ]);

}

!! Take cate that the ‘name’ key in “withMessages(” should match the file “name” specified in the resource !!

4- you should see error message when you submit the form

**sorry i could not do any better with the markdown formating :-) **

2 likes
MB's avatar
Level 2

@leodesign Thanks for the reply. Does that work in Nova too? About the markup, just use ``` when you start and end each coding block :)

jrmitch's avatar

For anyone that stumbles on this later, if you want the error message to show up as the "toast" message, you can add this class to app\Exceptions and throw one of these instead:

<?php
namespace App\Exceptions;

use Symfony\Component\HttpKernel\Exception\HttpException;

class InvalidActionException extends HttpException
{
    public function __construct(string $message = null)
    {
        parent::__construct(500, $message, null, [], 0);
    }
}

I don't love it because semantically it should be a 400 not a 500... but this is what gets the error to show so its what I'm using.

maxss's avatar

You can use the Exception class. I tried it in a Nova action and it throws a toast error notification.

use Exception;

...

throw_if(
    $validator->fails(),
    Exception::class,
    'Error message here ...'
);

...

1 like

Please or to participate in this conversation.