Weave 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

Auto Json Response Bundle Laravel Package

chrisyue/auto-json-response-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require chrisyue/auto-json-response-bundle
    

    Add to config/bundles.php (Symfony) or register via service provider (Laravel via config/app.php under providers):

    Chrisyue\AutoJsonResponseBundle\AutoJsonResponseBundle::class,
    
  2. First Use Case In a controller, return a simple array or object:

    public function index()
    {
        return ['name' => 'John', 'age' => 30]; // Auto-converted to JsonResponse
    }
    
    • No need for return response()->json() manually.
    • null returns a 204 No Content response.

Implementation Patterns

Core Workflows

  1. Automatic JSON Conversion

    • Return arrays/objects directly; the bundle handles serialization:
      return new UserModel(); // Auto-serialized to JSON
      
    • Exclude specific routes by tagging them with _json (e.g., Route::get('/exclude', [...], ['_json' => false])).
  2. Custom Status Codes

    • Append a status key to arrays/objects to override HTTP status:
      return ['data' => 'success', 'status' => 201]; // Returns 201
      
  3. Integration with Laravel

    • Override the Symfony listener in Laravel by publishing the bundle’s config:
      php artisan vendor:publish --provider="Chrisyue\AutoJsonResponseBundle\AutoJsonResponseBundle"
      
    • Extend the JsonResponseTransformer to add Laravel-specific logic (e.g., resource serialization).
  4. Conditional Responses

    • Use middleware to bypass the bundle for non-API routes:
      public function handle($request, Closure $next)
      {
          if (!$request->wantsJson()) {
              return $next($request);
          }
          return $next($request);
      }
      

Gotchas and Tips

Pitfalls

  1. Overriding Default Behavior

    • The bundle prioritizes JsonResponse or Response objects over automatic conversion. Return these explicitly to bypass:
      return response()->json(['error' => 'manual'], 500); // Ignores auto-conversion
      
  2. Circular References

    • Objects with circular references may cause serialization errors. Use ->toArray() or JsonSerializable:
      return (array) $objectWithCircles;
      
  3. Symfony vs. Laravel Quirks

    • Laravel’s Response factory differs from Symfony’s. Ensure the bundle’s JsonResponseTransformer is compatible:
      // Override in Laravel's service container:
      $this->app->bind(JsonResponseTransformer::class, function () {
          return new LaravelJsonResponseTransformer();
      });
      

Debugging Tips

  • Disable the Bundle Temporarily Comment out the bundle in config/bundles.php to isolate issues:

    // Chrisyue\AutoJsonResponseBundle\AutoJsonResponseBundle::class,
    
  • Check Event Listeners The bundle uses Symfony’s kernel.response event. Debug with:

    $this->app->booted(function () {
        $this->app['debug']->listen(function ($level, $message, array $context) {
            if (strpos($message, 'AutoJsonResponse') !== false) {
                // Log custom debug info
            }
        });
    });
    

Extension Points

  1. Custom Serialization Override the JsonResponseTransformer to add custom logic:

    // config/packages/chrisyue_auto_json_response.yaml
    chrisyue_auto_json_response:
        transformer: App\Services\CustomJsonTransformer
    
  2. Exclude Routes Globally Use route attributes or middleware to exclude paths:

    Route::get('/admin', [AdminController::class, 'index'])
        ->middleware('exclude.auto_json');
    
  3. Add Metadata Extend responses with metadata (e.g., timestamps):

    return ['data' => $user, 'meta' => ['timestamp' => now()]];
    
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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style