Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

HTTP Responses - Laravel - The PHP Framework ...

Laravel

Prologue
Release Notes
Upgrade Guide
Contribution Guide
Setup
Installation
Configuration
Homestead

https://laravel.com/docs/5.0/responses#response...

5.0

SEARCH

HTTP Responses
#
#
#
#

Basic Responses
Redirects
Other Responses
Response Macros

The Basics
Routing
Middleware
Controllers
Requests
Responses
Views
Architecture
Foundations

# Basic Responses
Returning Strings From Routes
The most basic response from a Laravel route is a string:

Route::get('/', function()
{

Service Providers
Service Container
Contracts
Facades
Request Lifecycle
Application Structure
Services
Authentication
Billing
Cache
Collections

1 of 8

return 'Hello World';


});

Creating Custom Responses


However, for most routes and controller actions, you will be
returning a full
Returning a full

Illuminate\Http\Response
Response

instance or a view.

instance allows you to customize the

response's HTTP status code and headers. A


inherits from the

Response

instance

Symfony\Component\HttpFoundation\Response

23/11/16 14:29

HTTP Responses - Laravel - The PHP Framework ...

Command Bus
Core Extension
Elixir
Encryption
Envoy
Errors & Logging
Events
Filesystem / Cloud
Storage
Hashing
Helpers
Localization
Mail
Package Development
Pagination
Queues
Session
Templates
Unit Testing
Validation
Database

https://laravel.com/docs/5.0/responses#response...

class, providing a variety of methods for building HTTP responses:

use Illuminate\Http\Response;

return (new Response($content, $status))


->header('Content-Type', $value);

For convenience, you may also use the

response

helper:

return response($content, $status)


->header('Content-Type', $value);

Note: For a full list of available

Response

methods, check out

its API documentation and the Symfony API documentation.

Sending A View In A Response


If you need access to the

Response

class methods, but want to

Basic Usage
Query Builder
Eloquent ORM
Schema Builder
Migrations & Seeding
Redis

return a view as the response content, you may use the

Artisan CLI

Attaching Cookies To Responses

Overview
Development

view

method for convenience:

return response()->view('hello')->header('Content-Type', $type)

return response($content)->withCookie(cookie('name', 'value'));

Method Chaining
Keep in mind that most

Response

methods are chainable, allowing

for the fluent building of responses:

2 of 8

23/11/16 14:29

HTTP Responses - Laravel - The PHP Framework ...

https://laravel.com/docs/5.0/responses#response...

return response()->view('hello')->header('Content-Type', $type)


->withCookie(cookie('name', 'value'));

# Redirects
Redirect responses are typically instances of the
Illuminate\Http\RedirectResponse

class, and contain the proper

headers needed to redirect the user to another URL.

Returning A Redirect
There are several ways to generate a
The simplest method is to use the

RedirectResponse

redirect

instance.

helper method. When

testing, it is not common to mock the creation of a redirect


response, so using the helper method is almost always acceptable:

return redirect('user/login');

Returning A Redirect With Flash Data


Redirecting to a new URL and flashing data to the session are
typically done at the same time. So, for convenience, you may
create a

RedirectResponse

instance and flash data to the session in

a single method chain:

return redirect('user/login')->with('message', 'Login Failed');

Redirecting To The Previous URL


You may wish to redirect the user to their previous location, for
example, aer a form submission. You can do so by using the

3 of 8

back

23/11/16 14:29

HTTP Responses - Laravel - The PHP Framework ...

https://laravel.com/docs/5.0/responses#response...

method:

return redirect()->back();

return redirect()->back()->withInput();

Returning A Redirect To A Named Route


When you call the
instance of

redirect

helper with no parameters, an

Illuminate\Routing\Redirector

you to call any method on the


to generate a
route

Redirector

RedirectResponse

is returned, allowing
instance. For example,

to a named route, you may use the

method:

return redirect()->route('login');

Returning A Redirect To A Named Route With Parameters


If your route has parameters, you may pass them as the second
argument to the

route

method.

// For a route with the following URI: profile/{id}

return redirect()->route('profile', [1]);

If you are redirecting to a route with an "ID" parameter that is being


populated from an Eloquent model, you may simply pass the
model itself. The ID will be extracted automatically:

return redirect()->route('profile', [$user]);

Returning A Redirect To A Named Route Using Named


Parameters

4 of 8

23/11/16 14:29

HTTP Responses - Laravel - The PHP Framework ...

https://laravel.com/docs/5.0/responses#response...

// For a route with the following URI: profile/{user}

return redirect()->route('profile', ['user' => 1]);

Returning A Redirect To A Controller Action


Similarly to generating

RedirectResponse

instances to named

routes, you may also generate redirects to controller actions:

return redirect()->action('App\Http\Controllers\HomeController@index'

Note: You do not need to specify the full namespace to the


controller if you have registered a root controller namespace
via

URL::setRootControllerNamespace

Returning A Redirect To A Controller Action With


Parameters
return redirect()->action('App\Http\Controllers\UserController@profile'

Returning A Redirect To A Controller Action Using Named


Parameters
return redirect()->action('App\Http\Controllers\UserController@profile'

# Other Responses
The

response

helper may be used to conveniently generate other

types of response instances. When the

response

helper is called

without arguments, an implementation of the

5 of 8

23/11/16 14:29

HTTP Responses - Laravel - The PHP Framework ...

https://laravel.com/docs/5.0/responses#response...

Illuminate\Contracts\Routing\ResponseFactory

contract is

returned. This contract provides several helpful methods for


generating responses.

Creating A JSON Response


The
to

json

method will automatically set the

application/json

Content-Type

header

return response()->json(['name' => 'Abigail', 'state' => 'CA'])

Creating A JSONP Response


return response()->json(['name' => 'Abigail', 'state' => 'CA'])
->setCallback($request->input('callback'));

Creating A File Download Response


return response()->download($pathToFile);

return response()->download($pathToFile, $name, $headers);

return response()->download($pathToFile)->deleteFileAfterSend(true

Note: Symfony HttpFoundation, which manages file


downloads, requires the file being downloaded to have an
ASCII file name.

# Response Macros
If you would like to define a custom response that you can re-use in

6 of 8

23/11/16 14:29

HTTP Responses - Laravel - The PHP Framework ...

https://laravel.com/docs/5.0/responses#response...

a variety of your routes and controllers, you may use the

macro

method on an implementation of
Illuminate\Contracts\Routing\ResponseFactory

For example, from a service provider's

boot

method:

<?php namespace App\Providers;

use Response;
use Illuminate\Support\ServiceProvider;

class ResponseMacroServiceProvider extends ServiceProvider {

/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
Response::macro('caps', function($value)
{
return Response::make(strtoupper($value));
});
}

The

macro

function accepts a name as its first argument, and a

Closure as its second. The macro's Closure will be executed when


calling the macro name from a
or the

response

ResponseFactory

implementation

helper:

return response()->caps('foo');

7 of 8

23/11/16 14:29

HTTP Responses - Laravel - The PHP Framework ...

Documentation

https://laravel.com/docs/5.0/responses#response...

Laracasts
News
Ecosystem

Forge

Conference

L A R A V E L I S A T R A D E M A R K O F T AY L O R O T W E L L . C O P Y R I G H T T AY L O R O T W E L L .

DESIGNED BY

8 of 8

23/11/16 14:29

You might also like