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

raditzfarhan/laravel-api-response

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require raditzfarhan/laravel-api-response
    

    No additional configuration or service provider registration is required (auto-discovered).

  2. First Use Case: Replace repetitive return response()->json() calls with the package’s fluent API. For example:

    // In a controller
    return response()->api()->success(['message' => 'User created']);
    

    Output:

    {
      "success": true,
      "message": "User created",
      "data": null
    }
    
  3. Where to Look First:


Implementation Patterns

Core Workflows

  1. Standard Responses:

    // Success with data
    return response()->api()->success($user);
    
    // Failure with message
    return response()->api()->failed('Invalid credentials');
    
    // Error with HTTP code
    return response()->api()->error('Unauthorized', 401);
    
  2. Chaining for Complex Responses:

    return response()->api()
        ->success()
        ->withMeta(['count' => 10])
        ->withLinks(['next' => url('/api/users?page=2')]);
    
  3. Controller-Level Helper: Create a base controller to enforce consistent responses:

    abstract class ApiController extends Controller {
        protected function respondSuccess($data = null) {
            return response()->api()->success($data);
        }
    }
    
  4. Exception Handling: Use middleware to catch exceptions and return formatted errors:

    // app/Http/Middleware/HandleApiErrors.php
    public function handle($request, Closure $next) {
        try {
            return $next($request);
        } catch (\App\Exceptions\ValidationException $e) {
            return response()->api()->error($e->getMessage(), 400);
        }
    }
    
  5. Facade for Global Access:

    use Raditzfarhan\ApiResponse\Facades\ApiResponse;
    
    // In a service or command
    ApiResponse::success(['data' => 'global']);
    

Integration Tips

  • API Resources: Combine with Laravel’s ApiResource for structured data:
    return response()->api()->success(new UserResource($user));
    
  • Pagination: Use withMeta() to include pagination links:
    return response()->api()
        ->success($users)
        ->withMeta(['pagination' => $users->links()]);
    
  • Testing: Mock responses in tests:
    $response = $this->get('/api/users');
    $response->assertJsonStructure([
        'success',
        'data',
        'message',
        'meta',
        'links'
    ]);
    

Gotchas and Tips

Pitfalls

  1. Overriding Default Structure:

    • The package defaults to a specific JSON structure. If you customize it (e.g., via config), ensure backward compatibility for existing clients.
    • Fix: Use config('api-response') to inspect the current structure before modifying.
  2. Facade vs. Macro Conflicts:

    • If both response()->api() and ApiResponse::success() are used, ensure they return identical responses. The facade internally uses the macro, so conflicts are rare but possible if the macro is overridden.
    • Fix: Stick to one style per project.
  3. Nested Data Serialization:

    • Complex nested objects (e.g., Eloquent relationships) may not serialize as expected. Use ->toArray() or ApiResource to flatten data.
    • Example:
      return response()->api()->success($user->load('posts')->toArray());
      
  4. HTTP Status Codes:

    • The package defaults to 200 for success and 400 for failures. Override explicitly for non-standard cases:
      return response()->api()->success($data, 201); // Created
      

Debugging

  • Check Config: Run php artisan config:clear if responses appear malformed after config changes.
  • Log Responses: Temporarily log the response object to debug:
    \Log::debug((string) response()->api()->success($data));
    
  • Validate Structure: Use dd(response()->api()->success()) to inspect the raw response object.

Tips

  1. Customize Response Structure: Publish the config and extend the default structure:

    php artisan vendor:publish --provider="Raditzfarhan\ApiResponse\ApiResponseServiceProvider" --tag="config"
    

    Then modify config/api-response.php:

    'structure' => [
        'success' => true,
        'data' => null,
        'errors' => null,
        'meta' => null,
        'links' => null,
        'status_code' => 200,
    ],
    
  2. Add Custom Methods: Extend the ApiResponse class to add project-specific methods:

    // app/Extensions/ApiResponseExtension.php
    namespace App\Extensions;
    
    use Raditzfarhan\ApiResponse\ApiResponse;
    
    class ApiResponseExtension extends ApiResponse {
        public function paginated($data) {
            return $this->success($data)->withMeta(['pagination' => true]);
        }
    }
    

    Register the extension in AppServiceProvider:

    ApiResponse::macro('paginated', function () {
        return (new ApiResponseExtension())->paginated(...func_get_args());
    });
    
  3. Performance:

    • For high-traffic APIs, cache the response structure in config to avoid repeated array merges.
    • Use ->withoutWrapping() to skip the JSON wrapper for non-API routes (e.g., webhooks).
  4. Documentation:

    • Add PHPDoc blocks to custom methods for IDE autocompletion:
      /**
       * @param mixed $data
       * @return \Illuminate\Http\JsonResponse
       */
      public function paginated($data) { ... }
      
  5. Testing:

    • Use ApiResponse::shouldReceive('success')->once() in PHPUnit to test interactions:
      ApiResponse::shouldReceive('success')
          ->once()
          ->with(['key' => 'value'])
          ->andReturnSelf();
      
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.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields
splash/sonata-admin
splash/metadata