Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle NotFoundHttpException in Laravel 8?

Tags:

laravel

I'm developing API in Laravel 8. I want to handle NotFoundHttpException to json response. But App\Exception\Handler updated in Laravel 8. By default render method does not exist. So I do not understand what I want to do. I have read in Laravel docs.

like image 473
Shahadat Hossain Avatar asked Nov 01 '25 01:11

Shahadat Hossain


1 Answers

You can use a custom callback as per the documentation, App\Exceptions\Handler:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

public function register()
{
    $this->renderable(function (NotFoundHttpException $e, $request) {
        return response()->json(...);
    });
}

If you send the correct accept header with your request the exception handler will return a JSON response already though.

Laravel 8.x Docs - Error Handling - Rendering Exceptions

like image 155
lagbox Avatar answered Nov 03 '25 09:11

lagbox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!