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

Shivamyadav's avatar

Want a reusable Laravel API error/exception/authorization handling structure.

Help me to find/suggest the better and more efficient way for handling all these cases without re writing every time.

0 likes
6 replies
JussiMannisto's avatar

Laravel has all of that built in. You can customize exception responses if needed. What is your issue exactly?

Shivamyadav's avatar

I have found some people were using the traits and some using the Laravel built in App\Exception\Handler render function to manage the different kinds of the scenarios for the authentication, Authorization and model exception etc for to avoid writing again and again those exceptions.

JussiMannisto's avatar

I'm afraid I still don't understand what you're talking about. What needs to be rewritten again and again?

Shivamyadav's avatar

I was talking about this

<?php

namespace App\Traits;

trait ApiResponses {
    protected function ok($message, $data = []) {
        return $this->success($message, $data, 200);
    }

    protected function success($message, $data = [], $statusCode = 200) {
        return response()->json([
            'data' => $data,
            'message' => $message,
            'status' => $statusCode
        ], $statusCode);
    }

    protected function error($message, $statusCode) {
        return response()->json([
            'message' => $message,
            'status' => $statusCode
        ], $statusCode);
    }
}

and for auto exception handling for this

in the register function to handle the different types of the exception instead of writing again and again the same logic in the controller for throw an error or server error etc.

martinbean's avatar

Want a reusable Laravel API error/exception/authorization handling structure.

@shivamyadav Laravel already has an exception handler that will consistently format any errors or exceptions thrown during a request. You don’t need to “handle” them at all.

1 like

Please or to participate in this conversation.