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

Json Request Bundle Laravel Package

symfony-bundles/json-request-bundle

Symfony bundle that decodes JSON request bodies and injects them into the Request parameter bag for easy controller handling. Supports common content types, validation-friendly input, and simplifies building JSON APIs by treating JSON like standard form data.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require symfony-bundles/json-request-bundle
    

    Register the bundle in config/app.php under providers:

    Symfony\Bundle\JsonRequestBundle\JsonRequestBundle::class,
    
  2. Enable JSON Request Parsing In app/Http/Kernel.php, add the middleware to the $middleware array:

    \Symfony\Bundle\JsonRequestBundle\Request\JsonRequestMiddleware::class,
    
  3. First Use Case: Accessing JSON Input In a controller, access JSON payload via $request->json():

    use Symfony\Component\HttpFoundation\Request;
    
    public function store(Request $request)
    {
        $data = $request->json(); // Returns array or null
        return response()->json($data);
    }
    

Implementation Patterns

1. JSON Request Handling Workflows

  • Validation & Sanitization Use Laravel’s built-in validation with $request->json():

    $validated = $request->validate([
        'name' => 'required|string',
        'email' => 'required|email',
    ]);
    
  • Nested JSON Structures Access nested data with array syntax:

    $userId = $request->json()['user']['id'];
    
  • Conditional JSON Logic Check if JSON exists before processing:

    if ($request->json()) {
        $data = $request->json();
    }
    

2. Integration with Laravel Features

  • Form Requests Extend Illuminate\Foundation\Http\FormRequest and use $this->json():

    public function rules()
    {
        return [
            'data.title' => 'required',
        ];
    }
    
  • API Resources Transform JSON responses with JsonResource:

    return new JsonResource(User::find(1));
    
  • Middleware for JSON-Only Routes Restrict routes to JSON input:

    Route::middleware(['json.request'])->post('/api/data', ...);
    

3. Custom JSON Parsing

  • Override Default Behavior Extend the middleware to modify JSON parsing:
    // app/Http/Middleware/CustomJsonMiddleware.php
    public function handle($request, Closure $next)
    {
        $request->setJson(json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR));
        return $next($request);
    }
    

Gotchas and Tips

Pitfalls

  • Empty JSON Payloads $request->json() returns null for empty payloads. Always check:

    if (!$request->json()) {
        return response()->json(['error' => 'No JSON data'], 400);
    }
    
  • Content-Type Mismatch Ensure requests include Content-Type: application/json. The middleware silently ignores non-JSON requests.

  • Large JSON Payloads Default json_decode() limits depth to 512. Adjust in middleware or use JSON_BIGINT_AS_STRING for large integers.

Debugging Tips

  • Inspect Raw Input Use $request->getContent() to debug raw JSON before parsing:

    dd($request->getContent());
    
  • Middleware Order Place JsonRequestMiddleware before validation middleware to ensure JSON is parsed early.

Extension Points

  • Custom JSON Decoder Override the decoder in middleware:

    $request->setJson(json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION));
    
  • Fallback to Form Input Merge JSON with form data:

    $input = array_merge($request->json() ?? [], $request->all());
    
  • Testing JSON Requests Use Http::fake() or json() helper in tests:

    $response = $this->json('POST', '/api/data', ['key' => 'value']);
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky