Views & Responses

Basic Responses

Returning Strings From Routes

  1. Route::get('/', function()
  2. {
  3. return 'Hello World';
  4. });

Creating Custom Responses

A Response instance inherits from the Symfony\Component\HttpFoundation\Response class, providing a variety of methods for building HTTP responses.

  1. $response = Response::make($contents, $statusCode);
  2. $response->header('Content-Type', $value);
  3. return $response;

If you need access to the Response class methods, but want to return a view as the response content, you may use the Response::view method for convenience:

  1. return Response::view('hello')->header('Content-Type', $type);

Attaching Cookies To Responses

  1. $cookie = Cookie::make('name', 'value');
  2. return Response::make($content)->withCookie($cookie);

Redirects

Returning A Redirect

  1. return Redirect::to('user/login');

Returning A Redirect With Flash Data

  1. return Redirect::to('user/login')->with('message', 'Login Failed');

Note: Since the with method flashes data to the session, you may retrieve the data using the typical Session::get method.

Returning A Redirect To A Named Route

  1. return Redirect::route('login');

Returning A Redirect To A Named Route With Parameters

  1. return Redirect::route('profile', array(1));

Returning A Redirect To A Named Route Using Named Parameters

  1. return Redirect::route('profile', array('user' => 1));

Returning A Redirect To A Controller Action

  1. return Redirect::action('[email protected]');

Returning A Redirect To A Controller Action With Parameters

  1. return Redirect::action('[email protected]', array(1));

Returning A Redirect To A Controller Action Using Named Parameters

  1. return Redirect::action('[email protected]', array('user' => 1));

Views

Views typically contain the HTML of your application and provide a convenient way of separating your controller and domain logic from your presentation logic. Views are stored in the app/views directory.

A simple view could look something like this:

  1. <!-- View stored in app/views/greeting.php -->
  2. <html>
  3. <body>
  4. <h1>Hello, <?php echo $name; ?></h1>
  5. </body>
  6. </html>

This view may be returned to the browser like so:

  1. Route::get('/', function()
  2. {
  3. return View::make('greeting', array('name' => 'Taylor'));
  4. });

The second argument passed to View::make is an array of data that should be made available to the view.

Passing Data To Views

  1. // Using conventional approach
  2. $view = View::make('greeting')->with('name', 'Steve');
  3. // Using Magic Methods
  4. $view = View::make('greeting')->withName('steve');

In the example above the variable $name would be accessible from the view, and would contain Steve.

If you wish, you may pass an array of data as the second parameter given to the make method:

  1. $view = View::make('greetings', $data);

You may also share a piece of data across all views:

  1. View::share('name', 'Steve');

Passing A Sub-View To A View

Sometimes you may wish to pass a view into another view. For example, given a sub-view stored at app/views/child/view.php, we could pass it to another view like so:

  1. $view = View::make('greeting')->nest('child', 'child.view');
  2. $view = View::make('greeting')->nest('child', 'child.view', $data);

The sub-view can then be rendered from the parent view:

  1. <html>
  2. <body>
  3. <h1>Hello!</h1>
  4. <?php echo $child; ?>
  5. </body>
  6. </html>

Determining If A View Exists

If you need to check if a view exists, use the View::exists method:

  1. if (View::exists('emails.customer'))
  2. {
  3. //
  4. }

View Composers

View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want bound to a given view each time that view is rendered throughout your application, a view composer can organize that code into a single location. Therefore, view composers may function like "view models" or "presenters".

Defining A View Composer

  1. View::composer('profile', function($view)
  2. {
  3. $view->with('count', User::count());
  4. });

Now each time the profile view is rendered, the count data will be bound to the view.

You may also attach a view composer to multiple views at once:

  1. View::composer(array('profile','dashboard'), function($view)
  2. {
  3. $view->with('count', User::count());
  4. });

If you would rather use a class based composer, which will provide the benefits of being resolved through the application IoC Container, you may do so:

  1. View::composer('profile', 'ProfileComposer');

A view composer class should be defined like so:

  1. class ProfileComposer {
  2. public function compose($view)
  3. {
  4. $view->with('count', User::count());
  5. }
  6. }

Defining Multiple Composers

You may use the composers method to register a group of composers at the same time:

  1. View::composers(array(
  2. 'AdminComposer' => array('admin.index', 'admin.profile'),
  3. 'UserComposer' => 'user',
  4. '[email protected]' => 'product'
  5. ));

Note: There is no convention on where composer classes may be stored. You are free to store them anywhere as long as they can be autoloaded using the directives in your composer.json file.

View Creators

View creators work almost exactly like view composers; however, they are fired immediately when the view is instantiated. To register a view creator, simply use the creator method:

  1. View::creator('profile', function($view)
  2. {
  3. $view->with('count', User::count());
  4. });

Special Responses

Creating A JSON Response

  1. return Response::json(array('name' => 'Steve', 'state' => 'CA'));

Creating A JSONP Response

  1. return Response::json(array('name' => 'Steve', 'state' => 'CA'))->setCallback(Input::get('callback'));

Creating A File Download Response

  1. return Response::download($pathToFile);
  2. return Response::download($pathToFile, $name, $headers);

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 a variety of your routes and controllers, you may use the Response::macro method:

  1. Response::macro('caps', function($value)
  2. {
  3. return Response::make(strtoupper($value));
  4. });

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 on the Response class:

  1. return Response::caps('foo');

You may define your macros in one of your app/start files. Alternatively, you may organize your macros into a separate file which is included from one of your start files.