0% found this document useful (0 votes)
6 views

03 Laravel Responses

Uploaded by

ttooffee23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

03 Laravel Responses

Uploaded by

ttooffee23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Laravel Response

Creating Responses
Attaching Headers to Responses
You may use the header method to add a series of headers to the response before sending it
back to the user:
return response($content)
->header('Content-Type', $type)
->header('X-Header-One', 'Header Value')
->header('X-Header-Two', 'Header Value');
Attaching Cookies to Responses
You may attach a cookie to an outgoing Illuminate\Http\Response instance using the cookie
method. You should pass the name, value, and the number of minutes the cookie should be
considered valid to this method:
return response('Hello World')->cookie(
'name', 'value', $minutes
);
Cookies and Encryption
By default, thanks to the Illuminate\Cookie\Middleware\EncryptCookies middleware, all
cookies generated by Laravel are encrypted and signed so that they can't be modified or read
by the client. If you would like to disable encryption for a subset of cookies generated by your
application, you may use the encryptCookies method in your application's bootstrap/app.php
file:
->withMiddleware(function (Middleware $middleware) {
$middleware->encryptCookies(except: [
'cookie_name',
]);
})
Redirects
Redirect responses are instances of the Illuminate\Http\RedirectResponse class, and contain
the proper headers needed to redirect the user to another URL. There are several ways to
generate a RedirectResponse instance. The simplest method is to use the global redirect helper:
Route::get('/dashboard', function () {
return redirect('/home/dashboard');
1
});
Redirecting to Named Routes
When you call the redirect helper with no parameters, an instance of
Illuminate\Routing\Redirector is returned, allowing you to call any method on the Redirector
instance. For example, to generate a RedirectResponse to a named route, you may use the route
method:
return redirect()->route('login');
Redirecting to Controller Actions
You may also generate redirects to controller actions. To do so, pass the controller and action
name to the action method:
use App\Http\Controllers\UserController;
return redirect()->action([UserController::class, 'index']);
Redirecting to External Domains
Sometimes you may need to redirect to a domain outside of your application. You may do so
by calling the away method, which creates a RedirectResponse without any additional URL
encoding, validation, or verification:
return redirect()->away('https://www.google.com');
Redirecting With Flashed Session Data
Redirecting to a new URL and flashing data to the session are usually done at the same time.
Typically, this is done after successfully performing an action when you flash a success
message to the session. For convenience, you may create a RedirectResponse instance and flash
data to the session in a single, fluent method chain:
Route::post('/user/profile', function () {
// ...
return redirect('/dashboard')->with('status', 'Profile updated!');
});
After the user is redirected, you may display the flashed message from the session. For
example, using Blade syntax:
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif

2
Other Response Types
The response helper may be used to generate other types of response instances. When the
response helper is called without arguments, an implementation of the
Illuminate\Contracts\Routing\ResponseFactory contract is returned. This contract provides
several helpful methods for generating responses.
View Responses
If you need control over the response's status and headers but also need to return a view as the
response's content, you should use the view method:
return response()
->view('hello', $data, 200)
->header('Content-Type', $type);
JSON Responses
The json method will automatically set the Content-Type header to application/json, as well
as convert the given array to JSON using the json_encode PHP function:
return response()->json([
'name' => 'Abigail',
'state' => 'CA',
]);
File Downloads
The download method may be used to generate a response that forces the user's browser to
download the file at the given path. The download method accepts a filename as the second
argument to the method, which will determine the filename that is seen by the user downloading
the file. Finally, you may pass an array of HTTP headers as the third argument to the method:
return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);
File Responses
The file method may be used to display a file, such as an image or PDF, directly in the user's
browser instead of initiating a download. This method accepts the absolute path to the file as
its first argument and an array of headers as its second argument:
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
Streamed Responses
By streaming data to the client as it is generated, you can significantly reduce memory usage
and improve performance, especially for very large responses. Streamed responses allow the
client to begin processing data before the server has finished sending it:

3
function streamedContent(): Generator {
yield 'Hello, ';
yield 'World!';
}

Route::get('/stream', function () {
return response()->stream(function (): void {
foreach (streamedContent() as $chunk) {
echo $chunk;
ob_flush();
flush();
sleep(2); // Simulate delay between chunks...
}
}, 200, ['X-Accel-Buffering' => 'no']);
});
Response Macros
If you would like to define a custom response that you can re-use in a variety of your routes
and controllers, you may use the macro method on the Response facade. Typically, you should
call this method from the boot method of one of your application's service providers, such as
the App\Providers\AppServiceProvider service provider:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider


{
/**
* Bootstrap any application services.
*/
public function boot(): void

4
{
Response::macro('caps', function (string $value) {
return Response::make(strtoupper($value));
});
}
}
The macro function accepts a name as its first argument and a closure as its second argument.
The macro's closure will be executed when calling the macro name from a ResponseFactory
implementation or the response helper:
return response()->caps('foo');

You might also like