Beginner LevelLaravel
How do you return HTTP Responses, JSON payloads, and File Downloads in Laravel?
❓ Interview Prompt: Explain response() helper, response()->json(), response()->download(), response()->streamDownload(), and status codes.
Laravel provides fluent response helpers to return HTTP headers, status codes, and formatted payloads:
•
JSON API Response: 'response()->json(["status" => "success"], 200)'
•
File Download: 'response()->download($filePath, "invoice.pdf")'
•
Stream Download: 'response()->streamDownload(callback, "report.csv")'
•
Custom Header: 'response("Content", 200)->header("Content-Type", "text/plain")'
Code Implementation Example
php
<?php
use IlluminateSupportFacadesStorage;
public function downloadInvoice($id)
{
$path = storage_path("app/invoices/inv-{$id}.pdf");
return response()->download($path, "Invoice-{$id}.pdf", [
'Content-Type' => 'application/pdf',
]);
}💡Returning binary PDF file download response with custom headers.
🎯 Interview Key Takeaway
Use response()->json() for API payloads and response()->download() for binary file attachments.
#Responses#JSON#Downloads#Beginner
Back to all Laravel Questions→