chrisyue/auto-json-response-bundle
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,
First Use Case In a controller, return a simple array or object:
public function index()
{
return ['name' => 'John', 'age' => 30]; // Auto-converted to JsonResponse
}
return response()->json() manually.null returns a 204 No Content response.Automatic JSON Conversion
return new UserModel(); // Auto-serialized to JSON
_json (e.g., Route::get('/exclude', [...], ['_json' => false])).Custom Status Codes
status key to arrays/objects to override HTTP status:
return ['data' => 'success', 'status' => 201]; // Returns 201
Integration with Laravel
php artisan vendor:publish --provider="Chrisyue\AutoJsonResponseBundle\AutoJsonResponseBundle"
JsonResponseTransformer to add Laravel-specific logic (e.g., resource serialization).Conditional Responses
public function handle($request, Closure $next)
{
if (!$request->wantsJson()) {
return $next($request);
}
return $next($request);
}
Overriding Default Behavior
JsonResponse or Response objects over automatic conversion. Return these explicitly to bypass:
return response()->json(['error' => 'manual'], 500); // Ignores auto-conversion
Circular References
->toArray() or JsonSerializable:
return (array) $objectWithCircles;
Symfony vs. Laravel Quirks
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();
});
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
}
});
});
Custom Serialization
Override the JsonResponseTransformer to add custom logic:
// config/packages/chrisyue_auto_json_response.yaml
chrisyue_auto_json_response:
transformer: App\Services\CustomJsonTransformer
Exclude Routes Globally Use route attributes or middleware to exclude paths:
Route::get('/admin', [AdminController::class, 'index'])
->middleware('exclude.auto_json');
Add Metadata Extend responses with metadata (e.g., timestamps):
return ['data' => $user, 'meta' => ['timestamp' => now()]];
How can I help you explore Laravel packages today?