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.
Installation:
composer require symfony/http-foundation
Laravel already includes this as a core dependency, so no additional installation is needed.
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
}
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.Where to Look First:
app('request')).$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
if ($request->isMethod('POST') && $request->isXmlHttpRequest()) {
// Handle AJAX POST
}
return new Response('Hello World', 200, ['Content-Type' => 'text/plain']);
return response()->json(['data' => $data], 200);
return new BinaryFileResponse($filePath, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="report.pdf"',
]);
$file = $request->file('document');
if ($file->isValid()) {
$file->move($storagePath);
} else {
// Handle error: $file->getErrorMessage()
}
$file = $request->files->get('large_file');
$file->moveTo($destination, true); // Overwrite if exists
$session = $request->getSession();
$session->set('user_id', 123);
$userId = $session->get('user_id');
$request->session()->flash('status', 'Task completed!');
$format = $request->getRequestFormat(); // 'json', 'xml', etc.
return response()->json($data, 200, [], true); // Force JSON
return redirect()->route('profile.show', ['user' => $user]);
return new RedirectResponse('https://example.com', 302);
$response = new StreamedResponse();
$response->setCallback(function () use ($filePath) {
echo file_get_contents($filePath);
});
return $response;
$response = new EventStreamResponse();
$response->setCallback(function () {
echo "data: Message 1\n\n";
flush();
sleep(1);
echo "data: Message 2\n\n";
flush();
});
return $response;
AppServiceProvider:
public function boot()
{
Request::macro('customMethod', function () {
return $this->getMethod() === 'CUSTOM';
});
}
Request/Response in middleware:
public function handle(Request $request, Closure $next)
{
$response = $next($request);
$response->headers->set('X-Custom-Header', 'value');
return $response;
}
JsonResponse for consistent API responses:
return new JsonResponse([
'data' => $resource->toArray($request),
'meta' => ['status' => 'success'],
]);
$request = Request::create('/test', 'GET', [], [], [], ['HTTP_AUTHORIZATION' => 'Bearer token']);
$response = $this->app->handle($request);
$response = $this->get('/api/data');
$response->assertStatus(200);
$response->assertJson(['key' => 'value']);
// Instead of:
$allInput = $request->request->all();
// Use:
$email = $request->request->get('email');
StreamedResponse or BinaryFileResponse to avoid memory issues with large files.cookie_lifetime is set in your session configuration (fixed in v8.0.7+):
'session' => [
'cookie_lifetime' => 3600, // 1 hour
],
// Configure in config/session.php:
'prefix' => 'laravel_',
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;
PATH_INFO can cause issues (fixed in v5.4.50+):
// Ensure your server sends valid PATH_INFO
try {
$url = new Url('https://example.com');
} catch (InvalidArgumentException $e) {
// Handle invalid URL
}
isValid() before processing:
if (!$file->isValid()) {
throw new \RuntimeException($file->getErrorMessage());
}
upload_max_filesize and post_max_size may restrict uploads. Use UploadedFile::move() carefully for large files:
$file->move($destination, true); // Overwrite if exists
$file->move($destination);
$file->delete(); // Clean up temp file
Cache-Control headers for static assets:
$response->setPublic();
$response->setMaxAge(3600); // Cache for 1 hour
Expires header must be set for SSE (fixed in v8.0.1+):
$response->headers->set('Expires', '0');
How can I help you explore Laravel packages today?