Home > Back-end >  How to return custom response for `Illuminate\Support\ItemNotFoundException`?
How to return custom response for `Illuminate\Support\ItemNotFoundException`?

Time:09-16

In my controller, I used the method firstOrFail() for a database query with Eloquent. When in debug mode, I get a Laravel error message with the content Illuminate\Support\ItemNotFoundException.

However, I'd like to return a redirect() or mabye back() instead of showing this error screen. How can I do that?

CodePudding user response:

use php try catch, to override the behaviour of error catching,

          try {
            // your functional code
            } catch (Illuminate\Support\ItemNotFoundException $exception ) {
            //your redirect command , the code here will be executed if there is an exception with type ItemNotFoundException 
            }

if you want to catch all errors, you need to use the General Exception class which is the parent of all Exceptions

          try {
            // your functional code
            } catch (\Exception $exception) {
            //your redirect command , the code here will be executed if there is any exception 
            }

if you want to get the exception message to log it or any customization , you can use the method : getMessage() , in our case will be $exception->getMessage()

CodePudding user response:

Instead of firstOrFail() use first() and use condition to redirect back, for example:

$item = Item::where('slug', $slug)->first();

if (! $item) {
    return redirect()->back();
}
  • Related