triquang/laravel-response-scaffold

Generate response scaffolding and exception handler.

Installs: 8

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/triquang/laravel-response-scaffold

2.0.0 2025-08-13 05:01 UTC

This package is auto-updated.

Last update: 2025-12-13 05:41:44 UTC


README

Latest Version on Packagist Total Downloads License

A Laravel Artisan command to quickly generate an API Response class, standardize response formats, and configure exception handling and guest redirects for APIs.

๐Ÿš€ Features

  • Create basic routes/api.php file if not exists.
  • Create standardized app/Support/Responses/ApiResponse.php file if not exists.
  • Configure Global Exception Handler in bootstrap/app.php to handle API errors:
    • AuthenticationException โ†’ 401 Unauthenticated
    • AuthorizationException โ†’ 403 Unauthorized
    • ModelNotFoundException โ†’ 404 Resource not found
    • NotFoundHttpException โ†’ 404 Endpoint not found
    • ValidationException โ†’ 422 Validation failed
    • Other errors โ†’ 500 Server Error (or return detailed message if APP_DEBUG=true)
  • Prevent Laravel from automatically redirecting unlogged API to web login page.
  • Works well on Laravel 11+ with configurations:
    • ->withRouting()
    • ->withExceptions()
    • ->withMiddleware()

๐Ÿ“ฆ Installation

Install via Composer (recommended to use --dev as this is a development tool):

composer require triquang/laravel-response-scaffold --dev

โš™๏ธ Usage

Run the Artisan command:

php artisan make:response-scaffold

This command will:

  1. Create routes/api.php if it does not exist.
  2. Create app/Support/Responses/ApiResponse.php if it does not exist.
  3. Add Api route configuration to bootstrap/app.php.
  4. Add redirectGuestsTo configuration to bootstrap/app.php.
  5. Add Global Exception Handler configuration to bootstrap/app.php.

๐Ÿ“‚ Output structure

After running, you will have:

app/
โ””โ”€โ”€ Support/
    โ””โ”€โ”€ Responses/
        โ””โ”€โ”€ ApiResponse.php
bootstrap/
โ””โ”€โ”€ app.php
routes/
โ””โ”€โ”€ api.php

๐Ÿ’ก Examples

How to use:

  1. Shorthand with parameter order
  2. Named parameters with arbitrary order (PHP 8+)
use App\Support\Responses\ApiResponse;

class Example
{
    public function shorthands()
    {
        // Just data
        ApiResponse::success($users);

        // With custom message
        ApiResponse::success($users, 'Users loaded');

        // With custom status code
        ApiResponse::success($user, 'User created', 201);

        // Full parameters
        ApiResponse::success($users, 'Users found', 200, ['page' => 3]);

        // Error cases
        ApiResponse::error('Server error');
        ApiResponse::error('User not found', [], 404);
        ApiResponse::error('Validation failed', $validator->errors(), 422);

        // With exception (debug)
        try {
            // some code
        } catch (Exception $e) {
            return ApiResponse::error('Something went wrong', [], 500, [], $e);
        }
    }

    public function namedParameters()
    {
        // Full parameters, in arbitrary order
        ApiResponse::success(
           data: $users, 
           message: 'Users found', 
           statusCode: 200, 
           meta: ['page' => 3]
        );

        // Error case
        ApiResponse::error(
            message: 'Something went wrong',
            errors: $validator->errors(),
            statusCode: 422,
            meta: ['s' => 2],
            exception: $e   // <- in try-catch {}, if needed
        );
    }
}

๐Ÿ’ก Tip: Named parameters make your code more readable and avoid mistakes when skipping optional arguments.

When there is an error like NotFoundHttpException, the API will return:

{
  "status": "error",
  "message": "Endpoint not found",
  "errors": [],
  "meta": {
    "url": "http://127.0.0.1:8000/api/not-exist"
  }
}

โœ… Requirements

  • PHP >= 8.0
  • Laravel 11 / 12
  • Composer

๐Ÿ“„ License

MIT ยฉ Nguyแป…n Trรญ Quang

๐Ÿ™Œ Contributing

PRs are welcome! Feel free to improve functionality or report issues via GitHub Issues.

๐Ÿ“ฌ Contact