Laravel Responses: Views, JSON and File Downloads
So far your controllers have returned plain text and arrays, and the browser showed them as raw JSON. That was fine for learning, but a real invoicing app needs more. The owner wants a proper invoice page with a heading and a table. The mobile app needs JSON, and it needs to know that the invoice was created successfully. The accountant wants to click a button and download all invoices as a file for Excel.
Each of these is a different kind of response, and Laravel has a simple way to produce all of them. In this lesson you will learn what a response is, and how to return views, JSON, custom headers and file downloads from your controllers.
What Is a Response?
When a browser visits your site, your app must answer with an HTTP response. A response has three parts: a status code that says what happened, headers that describe the content, and a body that holds the content itself.
HTTP/1.1 200 OK
Content-Type: application/json
{"invoice":1001,"client":"Sharma Traders","total":14750}
Here 200 OK is the status, Content-Type is a header, and the JSON text is the body. You saw in the Request Lifecycle lesson that the final step of every request is turning your return value into a response and sending it back. In this lesson you take control of that final step.
Laravel Converts What You Return
You do not always need to build a response yourself. Laravel looks at what your controller method returns and converts it:
return 'Hello'; // text response, status 200
return ['invoice' => 1001]; // JSON response, status 200
return view('invoices.show'); // HTML response from a view
This is why returning an array worked in the earlier lessons. When you need more control, such as a different status code or an extra header, you build the response with the response() helper.
The response() Helper
The response() helper creates a response object that you can adjust step by step. You pass the content and, optionally, the status code, then chain extra methods:
return response('Invoice not found', 404);
return response('Invoice saved', 201)
->header('X-Invoice-Number', 'INV-2026-4821');
The result is a normal response with the status code and header you asked for. The idea of chaining methods one after another is the same one you used with routes, like ->name() and ->whereNumber().
Returning Views
A view is a file that holds the HTML for a page. Views live in the resources/views folder, and you return one with the view() helper. A view file ends with .blade.php, because Laravel uses its Blade template engine to prepare it. You will study Blade fully in the next chapters, so here you only need the very basics.
Create the file resources/views/invoices/show.blade.php:
<h1>Invoice {{ $invoice['invoice'] }}</h1>
<p>Client: {{ $invoice['client'] }}</p>
<p>Amount: ₹ {{ number_format($invoice['amount']) }}</p>
<p>GST (18%): ₹ {{ number_format($invoice['gst']) }}</p>
<p>Total: ₹ {{ number_format($invoice['total']) }}</p>
The double curly braces print a value from PHP, and they also make the value safe to show in a page. The variable $invoice has to come from your controller, which is the next step.
Passing Data to a View
Pass the data as the second argument of view(), in an array. The array key becomes the variable name inside the view:
public function show(int $invoice)
{
$data = $this->invoiceService->find($invoice) ?? abort(404);
return view('invoices.show', ['invoice' => $data]);
}
Open http://localhost:8000/invoices/1001 and you will now see a real HTML page instead of JSON. The controller stayed short because the service did the work, and the view only displays the result.
You may also see two shorter ways to pass the same data. They behave identically:
return view('invoices.show')->with('invoice', $data);
$invoice = $data;
return view('invoices.show', compact('invoice'));
View Names and Folders
The view name is the file path inside resources/views, without .blade.php, and with dots in place of slashes:
view('invoices.show') -> resources/views/invoices/show.blade.php
view('invoices.index') -> resources/views/invoices/index.blade.php
view('admin.reports.sales') -> resources/views/admin/reports/sales.blade.php
Using the same word for the folder as your resource, like invoices, keeps views easy to find. It also matches the resource controller methods: index, create, show and edit each get a view with the same name.
Returning JSON
When your app talks to a mobile app or a JavaScript frontend, you return JSON. Returning an array already does this, but response()->json() lets you also set the status code:
public function store(Request $request)
{
$invoice = $this->invoiceService->create(
$request->input('client'),
$request->integer('amount'),
);
return response()->json($invoice, 201);
}
The second argument, 201, means “Created”. A client that receives it knows the new invoice exists. A bare 200 also works, but the specific code is more useful, because many tools read it to decide what to do next.
Here are the status codes you will use most often:
200 OK the request worked 201 Created a new record was saved 204 No Content it worked, and there is nothing to send back 400 Bad Request the request was malformed 401 Unauthorized the user is not logged in 403 Forbidden logged in, but not allowed 404 Not Found the record or page does not exist 422 Unprocessable Content validation failed (covered later) 500 Server Error something broke on the server
For a delete action, a common choice is 204 with no body:
public function destroy(int $invoice)
{
// Later: delete the invoice from the database
return response()->noContent();
}
JSON Error Messages
For a JSON client, a missing record should also be JSON, with a matching status:
return response()->json(['message' => 'Invoice not found'], 404);
The abort(404) call you used earlier also works and Laravel will return a suitable response. Writing the JSON yourself gives you control over the message. You will see how to keep API errors consistent in the API Validation & Error Handling lesson, and how to shape the JSON data itself in the API Resources lesson.
Setting Headers
A header is a small piece of information sent along with the response. Add one with header(), or add several at once with withHeaders():
return response()
->json($invoice, 201)
->header('X-Invoice-Number', 'INV-2026-4821');
return response()
->json($invoice)
->withHeaders([
'X-Invoice-Number' => 'INV-2026-4821',
'X-Company' => 'MasterPHP Traders',
]);
Custom headers beginning with X- are a convention for information that the standard headers do not cover. A mobile app can read them to get extra details without changing the JSON body.
File Downloads
Sometimes the response is a file, such as a PDF invoice or a CSV export. Laravel has helpers for the three common situations.
Generating a File on the Fly
If the content is created by your code, use streamDownload(). It sends the data to the browser as it is produced, so no file is saved on the server. This is a good fit for CSV exports:
public function export()
{
$invoices = $this->invoiceService->all();
return response()->streamDownload(function () use ($invoices) {
$out = fopen('php://output', 'w');
fputcsv($out, ['Number', 'Client', 'Amount']);
foreach ($invoices as $number => $invoice) {
fputcsv($out, [$number, $invoice['client'], $invoice['amount']]);
}
fclose($out);
}, 'invoices.csv', ['Content-Type' => 'text/csv']);
}
The second argument is the file name the user will see, and the third holds extra headers. Register the route above the resource line, as you learned in the Resource Controllers lesson:
Route::get('/invoices/export', [InvoiceController::class, 'export'])
->name('invoices.export');
Route::resource('invoices', InvoiceController::class);
Visit /invoices/export and the browser downloads invoices.csv, which opens directly in Excel.
Downloading an Existing File
If the file already exists on the server, such as a saved PDF, use download() with its path:
public function pdf(int $invoice)
{
$path = storage_path("app/private/invoices/invoice-{$invoice}.pdf");
abort_unless(file_exists($path), 404);
return response()->download($path, "invoice-{$invoice}.pdf");
}
The storage_path() helper gives the full path to Laravel’s storage folder. In a fresh Laravel project the default storage disk points to storage/app/private, and you will learn how disks work in the Filesystem & Storage Disks lesson. We check that the file exists first with abort_unless(), so a missing file becomes a clean 404 page. Creating the PDF itself comes in the capstone project.
Showing a File in the Browser
The file() method looks the same as download(), but the browser displays the file instead of saving it. This works for PDFs and images:
return response()->file($path);
Use download() when you want a save dialog, and file() when the user should view it first.
Choosing the Right Response
- Use
view()when a person will read a web page - Use an array or
response()->json()when a program, like a mobile app, will read the data - Use
response()->json($data, 201)when you need a specific status code - Use
response()->noContent()when there is nothing to send back - Use
streamDownload()for files that your code generates - Use
download()orfile()for files that already exist on the server
Redirects are also responses, and they get their own lesson next.
Common Mistakes
Mistake 1: View Not Found
return view('invoices.show');
If the file is missing, misspelled or in the wrong folder, Laravel throws:
InvalidArgumentException: View [invoices.show] not found.
Check the folder name, the file name and the .blade.php ending. Also check capital letters, because a Linux server treats Show.blade.php and show.blade.php as different files.
Mistake 2: Forgetting to Pass the Data
return view('invoices.show');
The view prints $invoice, but the controller never sent it. The page fails with:
ErrorException: Undefined variable $invoice
Pass the value in the second argument of view(), and make sure the array key matches the variable name used in the view.
Mistake 3: Downloading a File That Does Not Exist
return response()->download(storage_path('app/private/invoices/missing.pdf'));
If the file is not there, you get an error that includes the full server path:
Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException: The file "/var/www/app/storage/app/private/invoices/missing.pdf" does not exist
Check with file_exists() first and return a 404, as shown earlier. Never show a raw error like this to visitors on a live site.
Mistake 4: Using echo or dd() Before the Return
public function show(int $invoice)
{
echo 'Loading invoice...';
return response()->json($this->invoiceService->find($invoice));
}
The text is printed before the response starts, so the JSON body becomes broken, because the start of it is now the stray text. Do not print inside a controller that returns a response. For debugging, use the tools in the Debugging chapter.
Mistake 5: Returning 200 for Errors
return response()->json(['error' => 'Invoice not found']);
No error appears, but the status code is 200, which tells every client that everything worked. Apps and tools rely on the code, so send 404 for a missing record, and other codes for other problems.
Mistake 6: Building a File Path from User Input
$path = storage_path('app/private/invoices/' . $request->input('file'));
return response()->download($path);
A visitor could send ../../../.env as the file name and download your secret settings. Never use input directly in a file path. Look the file up using a value you control, like the invoice number, as the pdf() method does above.
Quick Summary
- A response has a status code, headers and a body.
- Laravel converts what you return: text, arrays and views all become responses.
- Use the
response()helper when you need a custom status code or header. - Return a view with
view('invoices.show', ['invoice' => $data]), using dots for folders. - Use
response()->json($data, 201)for JSON with a status code, andresponse()->noContent()for an empty 204. - Add headers with
header()orwithHeaders(). - Use
streamDownload()for generated files such as CSV, anddownload()for files already on the server. - Use
file()to show a PDF or image in the browser instead of downloading it. - Send the right status code. Use 404 for missing records, not 200 with an error message.
- Never build file paths from user input.
What’s Next
You now know how to send pages, JSON and files back to the visitor. But there is one more very common response: sending the user to a different page. After an invoice is saved, you do not want to show a blank page. You want to take the user back to the list and tell them it worked. In the next lesson, Redirects & Flash Session Data, you will learn how to redirect and how to show one-time success messages.