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

Json Form Laravel Package

mcfedr/json-form

Symfony bundle/trait that lets controllers handle forms submitted as JSON. Use JsonControllerTrait to create and process JSON-backed forms, accepting payloads shaped like normal form fields, then validate and persist as usual.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require mcfedr/json-form
    

    Add to composer.json if not auto-loaded:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Mcfedr\\JsonForm\\": "vendor/mcfedr/json-form/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case Bind JSON data to a Symfony form in Laravel:

    use Mcfedr\JsonForm\JsonFormBinder;
    
    $jsonData = '{"name":"John","email":"[email protected]"}';
    $form = $this->createForm(YourFormType::class);
    
    $binder = new JsonFormBinder();
    $form->submit($binder->bind($jsonData, $form));
    

Implementation Patterns

Workflow: JSON-to-Form Binding

  1. Request Handling Extract JSON from incoming requests (e.g., API payloads):

    $requestData = json_decode($request->getContent(), true);
    $jsonString = json_encode($requestData);
    
  2. Form Submission Bind JSON to a Symfony form:

    $form = $this->createForm(YourFormType::class);
    $form->submit($binder->bind($jsonString, $form));
    
  3. Validation & Processing Check if form is valid:

    if ($form->isSubmitted() && $form->isValid()) {
        $data = $form->getData();
        // Process $data (e.g., save to DB)
    }
    

Integration with Laravel Controllers

use Mcfedr\JsonForm\JsonFormBinder;

class ApiController extends Controller
{
    protected $binder;

    public function __construct(JsonFormBinder $binder)
    {
        $this->binder = $binder;
    }

    public function store(Request $request)
    {
        $form = $this->createForm(YourFormType::class);
        $form->submit($this->binder->bind($request->getContent(), $form));

        if ($form->isValid()) {
            return response()->json(['success' => true]);
        }
        return response()->json(['errors' => $form->getErrors()], 400);
    }
}

Dynamic Form Types

Useful for APIs with variable schemas:

$json = '{"type":"user","name":"Alice"}';
$formType = $json['type'] === 'user' ? UserFormType::class : GuestFormType::class;
$form = $this->createForm($formType);
$form->submit($binder->bind($json, $form));

Gotchas and Tips

Pitfalls

  1. JSON Parsing Errors

    • Ensure JSON is valid before binding:
      if (json_validate($jsonString)) {
          $form->submit($binder->bind($jsonString, $form));
      }
      
    • Use json_last_error() for debugging.
  2. Nested Data Mismatches

    • If JSON has nested keys (e.g., {"user":{"name":"John"}}), ensure your form type matches:
      # UserFormType.yaml
      user:
          type: entity
          class: App\Entity\User
      
  3. Case Sensitivity

    • JSON keys are case-sensitive. Match form field names exactly:
      // JSON: {"FirstName":"John"} → Form field must be "FirstName", not "firstName".
      

Debugging

  • Log Bound Data

    $boundData = $binder->bind($jsonString, $form);
    \Log::debug('Bound data:', [$boundData]);
    
  • Check Form Errors

    if (!$form->isValid()) {
        \Log::error('Form errors:', $form->getErrors(true));
    }
    

Extension Points

  1. Custom Binders Extend JsonFormBinder for custom logic:

    class CustomBinder extends JsonFormBinder
    {
        protected function transformData($data, FormInterface $form)
        {
            // Custom transformation (e.g., snake_case to camelCase)
            return parent::transformData($data, $form);
        }
    }
    
  2. Symfony Form Integration Use with Laravel's Symfony bridge:

    use Symfony\Component\Form\FormFactoryInterface;
    
    $formFactory = app(FormFactoryInterface::class);
    $form = $formFactory->create(YourFormType::class);
    
  3. API Resource Serialization Combine with Fractal/Zizaco/ApiResource for consistent JSON responses:

    $transformer = new YourTransformer($form->getData());
    return response()->json(Fractal::create($transformer)->toArray());
    

Configuration Quirks

  • No Laravel-Specific Config The package is agnostic to Laravel’s config. Use dependency injection for the binder:

    $this->app->bind(JsonFormBinder::class, function ($app) {
        return new JsonFormBinder();
    });
    
  • Form Type Prioritization If binding fails, verify:

    • The form type is registered in Symfony’s form registry.
    • The JSON structure aligns with the form’s expected data.
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.
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk
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