AI generated content percentage: 15%
In API development, multipart/form-data is usually fine on POST, but often breaks on PUT, PATCH, or DELETE.
Typical symptoms:
- fields are empty in update endpoints
- uploaded files are missing
- team ends up forcing update flows to
POSTonly
This code fixes that by manually parsing raw multipart payloads for non-POST requests, then rebuilding Laravel’s normal request structure.
-
app/Http/Middleware/ParseMultipartFormData.php
Main middleware.
It runs only when request method is notGET,HEAD, orPOST.
IfContent-Typecontainsmultipart/form-data, it:- reads raw request body
- parses it using
FormDataProcessor - adds parsed inputs into
$request->request - adds parsed files into
$request->files - recursively converts file arrays into
UploadedFileobjects
-
app/Core/FormDataProcessor.php
Multipart parser engine.
It splits body by boundary, reads headers, detects field name + optional filename, and maps:- normal form values into
$inputs - file content into temp files, returning file metadata (
name,type,tmp_name,size, etc.)
- normal form values into
-
app/Exceptions/ParsingMultipartFormDataExeption.php
Custom exception used when parsing fails.
- Register middleware (global or API group) in your HTTP kernel/pipeline:
\App\Http\Middleware\ParseMultipartFormData::class,- Send requests using
multipart/form-datawith methods likePUT/PATCH:
curl -X PATCH https://api.example.com/users/10 \
-F "name=John" \
-F "avatar=@/path/avatar.jpg"- In controller, access data normally:
$request->input('name');
$request->file('avatar');No special controller logic is needed after middleware is registered.