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

Http Foundation Laravel Package

symfony/http-foundation

Symfony HttpFoundation provides an object-oriented layer for working with HTTP: requests, responses, sessions, cookies, headers, and file uploads. It simplifies handling and testing web interactions while staying close to the HTTP specification.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require symfony/http-foundation
    

    Laravel already includes this as a core dependency, so no additional installation is needed.

  2. First Use Case: Access the current HTTP request in a Laravel controller:

    use Symfony\Component\HttpFoundation\Request;
    
    public function show(Request $request)
    {
        $method = $request->getMethod(); // "GET", "POST", etc.
        $query = $request->query->all(); // All query parameters
        $input = $request->request->all(); // All POST/PUT data
    }
    
  3. Key Classes to Explore:

    • Request: Handles incoming HTTP requests (headers, body, query, etc.).
    • Response: Constructs HTTP responses (status codes, headers, content).
    • JsonResponse: For API responses.
    • UploadedFile: For file upload handling.
    • Session: Session management.
  4. Where to Look First:


Implementation Patterns

Core Workflows

1. Request Handling

  • Accessing Data:
    $request = app('request'); // Laravel's Request instance (extends Symfony's Request)
    $path = $request->path(); // Current path
    $header = $request->headers->get('Authorization'); // Headers
    $file = $request->files->get('avatar'); // Uploaded files
    
  • Custom Request Logic:
    if ($request->isMethod('POST') && $request->isXmlHttpRequest()) {
        // Handle AJAX POST
    }
    

2. Response Construction

  • Basic Response:
    return new Response('Hello World', 200, ['Content-Type' => 'text/plain']);
    
  • JSON Response (Laravel Shortcut):
    return response()->json(['data' => $data], 200);
    
  • File Downloads:
    return new BinaryFileResponse($filePath, 200, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'attachment; filename="report.pdf"',
    ]);
    

3. File Uploads

  • Validation:
    $file = $request->file('document');
    if ($file->isValid()) {
        $file->move($storagePath);
    } else {
        // Handle error: $file->getErrorMessage()
    }
    
  • Streaming Uploads:
    $file = $request->files->get('large_file');
    $file->moveTo($destination, true); // Overwrite if exists
    

4. Session Management

  • Accessing Session:
    $session = $request->getSession();
    $session->set('user_id', 123);
    $userId = $session->get('user_id');
    
  • Flash Messages:
    $request->session()->flash('status', 'Task completed!');
    

5. Content Negotiation

  • Auto-Detect Format:
    $format = $request->getRequestFormat(); // 'json', 'xml', etc.
    return response()->json($data, 200, [], true); // Force JSON
    

6. Redirects

  • Named Routes:
    return redirect()->route('profile.show', ['user' => $user]);
    
  • External URLs:
    return new RedirectResponse('https://example.com', 302);
    

7. Streaming Responses

  • Large File Streaming:
    $response = new StreamedResponse();
    $response->setCallback(function () use ($filePath) {
        echo file_get_contents($filePath);
    });
    return $response;
    
  • Server-Sent Events (SSE):
    $response = new EventStreamResponse();
    $response->setCallback(function () {
        echo "data: Message 1\n\n";
        flush();
        sleep(1);
        echo "data: Message 2\n\n";
        flush();
    });
    return $response;
    

Integration Tips

Laravel-Specific Patterns

  • Service Providers: Extend Symfony’s components in Laravel’s AppServiceProvider:
    public function boot()
    {
        Request::macro('customMethod', function () {
            return $this->getMethod() === 'CUSTOM';
        });
    }
    
  • Middleware: Use Symfony’s Request/Response in middleware:
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        $response->headers->set('X-Custom-Header', 'value');
        return $response;
    }
    
  • API Resources: Leverage JsonResponse for consistent API responses:
    return new JsonResponse([
        'data' => $resource->toArray($request),
        'meta' => ['status' => 'success'],
    ]);
    

Testing

  • Mocking Requests:
    $request = Request::create('/test', 'GET', [], [], [], ['HTTP_AUTHORIZATION' => 'Bearer token']);
    $response = $this->app->handle($request);
    
  • Testing Responses:
    $response = $this->get('/api/data');
    $response->assertStatus(200);
    $response->assertJson(['key' => 'value']);
    

Performance

  • Avoid Loading Unnecessary Data:
    // Instead of:
    $allInput = $request->request->all();
    
    // Use:
    $email = $request->request->get('email');
    
  • Stream Large Responses: Use StreamedResponse or BinaryFileResponse to avoid memory issues with large files.

Gotchas and Tips

Pitfalls

1. Session Handling Quirks

  • Cookie Lifetime: Ensure cookie_lifetime is set in your session configuration (fixed in v8.0.7+):
    'session' => [
        'cookie_lifetime' => 3600, // 1 hour
    ],
    
  • Redis/Memcached Prefixing: Avoid double-prefixing of session keys (fixed in v8.0.4+):
    // Configure in config/session.php:
    'prefix' => 'laravel_',
    
  • PDO Session Handler: Use utf8mb4 collation to avoid charset mismatches (fixed in v8.0.5+):
    CREATE TABLE sessions (
        id VARCHAR(255) NOT NULL PRIMARY KEY,
        data LONGTEXT NOT NULL,
        updated_at DATETIME NOT NULL
    ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
    

2. Request Parsing Issues

  • PathInfo Handling: Empty or malformed PATH_INFO can cause issues (fixed in v5.4.50+):
    // Ensure your server sends valid PATH_INFO
    
  • Host/Scheme Parsing: Invalid URLs may throw exceptions (fixed in v8.0.0-RC1+):
    try {
        $url = new Url('https://example.com');
    } catch (InvalidArgumentException $e) {
        // Handle invalid URL
    }
    

3. File Uploads

  • Error Handling: Always check isValid() before processing:
    if (!$file->isValid()) {
        throw new \RuntimeException($file->getErrorMessage());
    }
    
  • Large File Limits: PHP’s upload_max_filesize and post_max_size may restrict uploads. Use UploadedFile::move() carefully for large files:
    $file->move($destination, true); // Overwrite if exists
    
  • Temporary Files: Uploaded files are stored in PHP’s temp directory. Delete them after processing:
    $file->move($destination);
    $file->delete(); // Clean up temp file
    

4. Response Headers

  • Caching Headers: Ensure proper Cache-Control headers for static assets:
    $response->setPublic();
    $response->setMaxAge(3600); // Cache for 1 hour
    
  • EventStream Headers: Expires header must be set for SSE (fixed in v8.0.1+):
    $response->headers->set('Expires', '0');
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport