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

defelper's avatar

Override Default Exceptions - Laravel 11.x

I am venturing into studying Laravel and I am having a problem overriding an exception.

I have the following route:

Route::get('read-article/{article}', [\App\Http\Controllers\Api\v1\ArticleController::class, 'show']);

And the controller code is:

public function show(Article $article)
{
    if ($article) {
        return response()->json([
            'status' => HttpFoundationResponse::HTTP_OK,
            'data' => $article,
        ], HttpFoundationResponse::HTTP_OK);
    }
}

When I search for an article that does not exist in the database, the API returns a NotFoundHttpException. I would like to override this exception and return a custom JSON response.

According to the Laravel documentation (docs/11.x/errors#renderable-exceptions), I created a NotFoundHttpException.php file in App/Exceptions but I still keep getting the default exception return. Is it necessary to configure this override somewhere?

My NotFoundHttpException file :

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Str;

class NotFoundHttpException extends Exception
{
    /**
     * Report the exception.
     */
    public function report(): bool
    {
        // ...
        return false;
    }

    /**
     * Render the exception into an HTTP response.
     */
    public function render(Request $request): Response|bool
    {
        if ($request->is('api/*') && ($this->getPrevious() instanceof \Illuminate\Database\Eloquent\ModelNotFoundException)) {
            $model = Str::afterLast($this->getPrevious()->getModel(), '\'); //extract Model name

            return response()->json(['message' => $model.' not found', 'status' => 404]);
        }

        return false;
    }
}

0 likes
1 reply

Please or to participate in this conversation.