Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Api Response Laravel Package

stackmasteraliza/laravel-api-response

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require stackmasteraliza/laravel-api-response
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Stackmasteraliza\ApiResponse\ApiResponseServiceProvider" --tag="config"
    
  2. First Use Case: Replace manual return response()->json() calls with the fluent builder in your controller:

    use Stackmasteraliza\ApiResponse\ApiResponse;
    
    public function show(User $user)
    {
        return ApiResponse::success($user)->withMeta(['custom' => 'value']);
    }
    
  3. Key Files to Review:

    • config/api-response.php (for customization)
    • app/Http/Controllers/Concerns/RespondsWithApiResponse.php (trait for auto-injection)

Implementation Patterns

Core Workflows

1. Controller Integration

Use the trait in your base controller or individual controllers:

use Stackmasteraliza\ApiResponse\Concerns\RespondsWithApiResponse;

class UserController extends Controller
{
    use RespondsWithApiResponse;

    public function index()
    {
        return $this->success(User::all());
    }
}

2. Fluent Response Building

Chain methods for complex responses:

return ApiResponse::success($data)
    ->withMeta(['pagination' => $data->appends(request()->query())])
    ->withLinks(['next' => url()->current() . '?page=2'])
    ->setStatusCode(201);

3. Validation Error Handling

Replace manual validation error formatting:

public function store(Request $request)
{
    $validated = $request->validate(User::$rules);
    return $this->error('Validation failed', $validated->errors(), 422);
}

4. Pagination Integration

Automatically attach pagination metadata:

return ApiResponse::success(User::paginate(10))
    ->withPagination();

5. Exception Handling

Override default exception responses:

// In App/Exceptions/Handler.php
public function render($request, Throwable $exception)
{
    return ApiResponse::error('Unauthorized', [], 401);
}

Advanced Patterns

Custom Response Types

Extend the base response class:

class CustomResponse extends ApiResponse
{
    public function withCustomData(array $data)
    {
        return $this->withData(['custom' => $data]);
    }
}

Dynamic Meta Data

Use closures for lazy-loaded metadata:

return ApiResponse::success($data)
    ->withMeta(fn() => ['count' => User::count()]);

API Versioning

Leverage middleware to set version-specific responses:

// In routes/api.php
Route::middleware(['api-version' => 'v1'])->group(...);

Testing

Mock responses in tests:

$response = $this->get('/users')
    ->assertJsonStructure([
        'data' => [],
        'meta' => [],
        'links' => [],
    ]);

Gotchas and Tips

Common Pitfalls

  1. Pagination Conflicts

    • If using withPagination(), ensure your collection/length-aware paginator is properly configured.
    • Fix: Explicitly pass the paginator instance:
      ApiResponse::success(User::paginate(10))->withPagination(User::paginate(10));
      
  2. Caching Headers

    • The package adds default caching headers. Disable with:
      ApiResponse::success($data)->disableCaching();
      
  3. Swagger/Postman Export

    • Requires stackmasteraliza/laravel-api-docs (separate package). Ensure both are installed:
      composer require stackmasteraliza/laravel-api-docs
      
  4. Trait Method Conflicts

    • If using RespondsWithApiResponse trait, avoid naming controller methods success() or error() to prevent conflicts.
  5. Status Code Overrides

    • Be explicit with status codes to avoid HTTP 200 defaults:
      ApiResponse::error('Not Found', [], 404);
      

Debugging Tips

  1. Response Inspection Use dd() to inspect the response object before sending:

    $response = ApiResponse::success($data)->withMeta(['debug' => true]);
    dd($response->toArray());
    
  2. Config Overrides Temporarily override config in bootstrap/app.php:

    $app->bind('api-response', fn() => new \Stackmasteraliza\ApiResponse\ApiResponse([
        'default_status' => 200,
        'include_links' => false,
    ]));
    
  3. Middleware Debugging Check if middleware is interfering with responses:

    // In App/Http/Kernel.php
    protected $middleware = [
        // Disable ApiResponseMiddleware temporarily
    ];
    

Extension Points

  1. Custom Response Formats Override the render() method in a service provider:

    ApiResponse::macro('customFormat', function($data) {
        return $this->withData(['formatted' => $data]);
    });
    
  2. Global Meta Data Add default meta data via config:

    'default_meta' => [
        'api_version' => '1.0.0',
        'timestamp' => now()->toIso8601String(),
    ],
    
  3. Exception Mappings Extend exception handling in App/Exceptions/Handler.php:

    public function register()
    {
        ApiResponse::extendExceptionHandling(function($request, Throwable $exception) {
            if ($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
                return ApiResponse::error('Resource not found', [], 404);
            }
        });
    }
    
  4. Localization Customize error messages via language files:

    // resources/lang/en/api.php
    'errors' => [
        'validation' => 'The given data failed validation.',
    ],
    
  5. Performance Optimization Disable unnecessary features in production:

    // config/api-response.php
    'debug' => env('APP_DEBUG', false),
    'include_links' => env('API_INCLUDE_LINKS', false),
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager