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 Http Form Bundle Laravel Package

elao/json-http-form-bundle

Symfony bundle that lets Forms handle JSON POST/PUT/PATCH/DELETE requests. Automatically detects JSON content-type, decodes request body, and submits data to your form; falls back to default HttpFoundation handling for normal GET/POST.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require elao/json-http-form-bundle
    

    Add to config/bundles.php:

    Elao\JsonHttpFormBundle\ElaoJsonHttpFormBundle::class => ['all' => true],
    
  2. Enable JSON Support In your FormType class, add:

    use Elao\JsonHttpFormBundle\Form\JsonHttpFormTrait;
    
    class MyFormType extends AbstractType
    {
        use JsonHttpFormTrait;
    
        // ...
    }
    
  3. First Use Case Submit a JSON payload via POST/PUT:

    {
        "name": "John Doe",
        "email": "john@example.com"
    }
    

    The bundle automatically binds JSON data to form fields (matching field names).


Implementation Patterns

Workflow: JSON Form Submission

  1. Frontend Use fetch() or Axios to send JSON:

    fetch('/submit-form', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: 'Alice', email: 'alice@example.com' })
    });
    
  2. Backend Laravel routes handle the request:

    #[Route('/submit-form', methods: ['POST'])]
    public function submit(Request $request, MyFormType $form): Response
    {
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            // Process data: $form->getData()
        }
        return $this->json($form->getErrors());
    }
    

Integration Tips

  • Hybrid Forms: Combine JSON and traditional HTML forms by checking $request->isJson().
  • Validation: Use Symfony’s JsonValidation constraint for nested JSON:
    #[Assert\JsonValidation(
        new Expression('/^(\d{3}-\d{2}-\d{4})$/'),
        message: 'Invalid format'
    )]
    private $ssn;
    
  • CSRF Protection: JSON requests require X-CSRF-Token header (Symfony’s default behavior).

Gotchas and Tips

Pitfalls

  1. CSRF Mismatch

    • JSON requests must include the CSRF token in headers:
      headers: {
          'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content,
          'Content-Type': 'application/json'
      }
      
    • Fix: Ensure your frontend fetches the token (Symfony’s default csrf_token meta tag).
  2. Field Name Mismatch

    • JSON keys must match form field names (case-sensitive).
    • Debug: Use dd($request->request->all()) to verify incoming data.
  3. Nested JSON

    • Deeply nested JSON (e.g., {"user": {"name": "Bob"}}) requires explicit binding:
      $form->add('user', CollectionType::class, [
          'entry_type' => UserType::class,
          'allow_add' => true,
          'by_reference' => false,
      ]);
      

Debugging

  • Enable Debugging: Set ELAO_JSON_HTTP_FORM_DEBUG to true in .env to log JSON binding issues.
  • Validation Errors: Check $form->getErrors(true) for nested JSON validation failures.

Extension Points

  1. Custom JSON Parsing Override JsonHttpFormTrait::bindJsonData() to handle custom JSON structures:

    protected function bindJsonData(array $jsonData, array $options): void
    {
        $this->data = $jsonData['custom_key'] ?? [];
    }
    
  2. Event Listeners Use Symfony events to intercept JSON binding:

    $eventDispatcher->addListener(
        JsonHttpFormEvents::JSON_BIND,
        function (JsonBindEvent $event) {
            $event->setData($event->getData()['transformed']);
        }
    );
    
  3. Configuration Override default behavior in config/packages/elao_json_http_form.yaml:

    elao_json_http_form:
        strict_mode: false  # Allow partial JSON binding
        allowed_methods: ['POST', 'PUT', 'PATCH']  # Customize HTTP methods
    
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