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

Multipart Form Data Parser Laravel Package

kekos/multipart-form-data-parser

Parse multipart/form-data bodies in PHP, including raw HTTP input. Useful for handling file uploads and form fields when your environment doesn’t populate $_FILES/$_POST (e.g., non-standard servers, PUT/PATCH requests).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require kekos/multipart-form-data-parser
    

    No additional configuration is required—just autoload the package.

  2. Basic Usage Parse a raw multipart request body (e.g., from $request->getContent() in Laravel):

    use Kekos\MultipartFormDataParser\Parser;
    
    $parser = new Parser();
    $parsedData = $parser->parse($rawRequestBody);
    

    Output will be an associative array with keys like:

    • files (for uploaded files)
    • fields (for form fields)
  3. First Use Case: File Uploads Handle a file upload endpoint:

    $rawBody = $request->getContent();
    $parsed = $parser->parse($rawBody);
    
    foreach ($parsed['files'] as $file) {
        $path = $file->move(storage_path('app/uploads'), $file->getClientOriginalName());
    }
    

Implementation Patterns

Workflow: Parsing in Laravel Controllers

  1. Extract Raw Body Laravel’s Illuminate\Http\Request provides $request->getContent() for raw body access.

    $rawBody = $request->getContent();
    
  2. Parse and Validate

    $parser = new Parser();
    $data = $parser->parse($rawBody);
    
    if (empty($data['files'])) {
        return response()->json(['error' => 'No files uploaded'], 400);
    }
    
  3. Process Files/Fields

    • Files: Iterate $data['files'] (instances of UploadedFile or similar).
    • Fields: Access $data['fields'] as a flat array.
  4. Integration with Laravel’s Request For seamless use, extend Laravel’s Request class:

    // app/Providers/AppServiceProvider.php
    use Kekos\MultipartFormDataParser\Parser;
    
    public function boot()
    {
        Request::macro('parseMultipart', function () {
            $parser = new Parser();
            return $parser->parse($this->getContent());
        });
    }
    

    Usage:

    $data = $request->parseMultipart();
    

Advanced: Custom File Handling

Override default file handling (e.g., for S3 uploads):

foreach ($data['files'] as $file) {
    $s3->putObject([
        'Bucket' => 'my-bucket',
        'Key'    => $file->getClientOriginalName(),
        'Body'   => fopen($file->getPathname(), 'r'),
    ]);
}

Gotchas and Tips

Pitfalls

  1. Boundary Detection

    • The parser relies on the Content-Type boundary. If malformed, parsing fails silently.
    • Fix: Validate the boundary exists in the raw body before parsing.
  2. Large File Handling

    • The package may not stream files by default (check memory limits).
    • Tip: Use Symfony\Component\HttpFoundation\File\UploadedFile for streaming:
      $file = new UploadedFile($tempPath, $file->getClientOriginalName());
      
  3. Nested Multipart

    • This parser does not support nested multipart (e.g., multipart within a file).
    • Workaround: Pre-process the request or use a dedicated library like league/mime-type-detection.

Debugging

  • Log Raw Body: Add this to debug malformed requests:
    \Log::debug('Raw body:', [$request->getContent()]);
    
  • Boundary Mismatch: Ensure the Content-Type header matches the actual boundary in the body.

Extension Points

  1. Custom File Classes Replace the default file object by extending the parser:

    $parser = new Parser();
    $parser->setFileClass(MyCustomUploadedFile::class);
    
  2. Field Validation Validate parsed fields using Laravel’s Validator:

    $validator = Validator::make($data['fields'], [
        'email' => 'required|email',
    ]);
    
  3. Performance For high-traffic APIs, instantiate the parser once (e.g., in a service container):

    $app->singleton(Parser::class, function () {
        return new Parser();
    });
    
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata