Laravel 8 and below:
There's a method render() in App\Exceptions class:
public function render($request, Exception $exception) { if ($request->wantsJson() || $request->is('api/*')) { if ($exception instanceof ModelNotFoundException) { return response()->json(['message' => 'Item Not Found'], 404); } if ($exception instanceof AuthenticationException) { return response()->json(['message' => 'unAuthenticated'], 401); } if ($exception instanceof ValidationException) { return response()->json(['message' => 'UnprocessableEntity', 'errors' => []], 422); } if ($exception instanceof NotFoundHttpException) { return response()->json(['message' => 'The requested link does not exist'], 400); } } return parent::render($request, $exception); }
Laravel 9 and above:
There's a method register() in App\Exceptions class:
public function register(){ $this->renderable(function (ModelNotFoundException $e, $request) { if ($request->wantsJson() || $request->is('api/*')) { return response()->json(['message' => 'Item Not Found'], 404); } }); $this->renderable(function (AuthenticationException $e, $request) { if ($request->wantsJson() || $request->is('api/*')) { return response()->json(['message' => 'unAuthenticated'], 401); } }); $this->renderable(function (ValidationException $e, $request) { if ($request->wantsJson() || $request->is('api/*')) { return response()->json(['message' => 'UnprocessableEntity', 'errors' => []], 422); } }); $this->renderable(function (NotFoundHttpException $e, $request) { if ($request->wantsJson() || $request->is('api/*')) { return response()->json(['message' => 'The requested link does not exist'], 400); } });}
Enjoyed This Tip?
Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.
Recent Courses
How to Build Laravel 12 API From Scratch
28 lessons
1 h 21 min
Claude Code for Laravel Projects: Crash Course
8 lessons
48 min
Laravel HTTP Client and 3rd-Party APIs
7 lessons
50 min