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.
Installation
composer require elao/json-http-form-bundle
Add to config/bundles.php:
Elao\JsonHttpFormBundle\ElaoJsonHttpFormBundle::class => ['all' => true],
Enable JSON Support
In your FormType class, add:
use Elao\JsonHttpFormBundle\Form\JsonHttpFormTrait;
class MyFormType extends AbstractType
{
use JsonHttpFormTrait;
// ...
}
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).
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' })
});
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());
}
$request->isJson().JsonValidation constraint for nested JSON:
#[Assert\JsonValidation(
new Expression('/^(\d{3}-\d{2}-\d{4})$/'),
message: 'Invalid format'
)]
private $ssn;
X-CSRF-Token header (Symfony’s default behavior).CSRF Mismatch
headers: {
'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content,
'Content-Type': 'application/json'
}
csrf_token meta tag).Field Name Mismatch
dd($request->request->all()) to verify incoming data.Nested JSON
{"user": {"name": "Bob"}}) requires explicit binding:
$form->add('user', CollectionType::class, [
'entry_type' => UserType::class,
'allow_add' => true,
'by_reference' => false,
]);
ELAO_JSON_HTTP_FORM_DEBUG to true in .env to log JSON binding issues.$form->getErrors(true) for nested JSON validation failures.Custom JSON Parsing
Override JsonHttpFormTrait::bindJsonData() to handle custom JSON structures:
protected function bindJsonData(array $jsonData, array $options): void
{
$this->data = $jsonData['custom_key'] ?? [];
}
Event Listeners Use Symfony events to intercept JSON binding:
$eventDispatcher->addListener(
JsonHttpFormEvents::JSON_BIND,
function (JsonBindEvent $event) {
$event->setData($event->getData()['transformed']);
}
);
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
How can I help you explore Laravel packages today?