HTTP Controllers

Introduction

Instead of defining all of your request handling logic in a single routes.php file, you may wish to organize this behavior using Controller classes. Controllers can group related HTTP request handling logic into a class. Controllers are typically stored in the app/Http/Controllers directory.

Basic Controllers

Here is an example of a basic controller class:

  1. <?php namespace App\Http\Controllers;
  2. use App\Http\Controllers\Controller;
  3. class UserController extends Controller {
  4. /**
  5. * Show the profile for the given user.
  6. *
  7. * @param int $id
  8. * @return Response
  9. */
  10. public function showProfile($id)
  11. {
  12. return view('user.profile', ['user' => User::findOrFail($id)]);
  13. }
  14. }

We can route to the controller action like so:

  1. Route::get('user/{id}', '[email protected]');

Note: All controllers should extend the base controller class.

Controllers & Namespaces

It is very important to note that we did not need to specify the full controller namespace, only the portion of the class name that comes after the App\Http\Controllers namespace "root". By default, the RouteServiceProvider will load the routes.php file within a route group containing the root controller namespace.

If you choose to nest or organize your controllers using PHP namespaces deeper into the App\Http\Controllers directory, simply use the specific class name relative to the App\Http\Controllers root namespace. So, if your full controller class is App\Http\Controllers\Photos\AdminController, you would register a route like so:

  1. Route::get('foo', 'Photos\[email protected]');

Naming Controller Routes

Like Closure routes, you may specify names on controller routes:

  1. Route::get('foo', ['uses' => '[email protected]', 'as' => 'name']);

URLs To Controller Actions

To generate a URL to a controller action, use the action helper method:

  1. $url = action('App\Http\Controllers\[email protected]');

If you wish to generate a URL to a controller action while using only the portion of the class name relative to your controller namespace, register the root controller namespace with the URL generator:

  1. URL::setRootControllerNamespace('App\Http\Controllers');
  2. $url = action('[email protected]');

You may access the name of the controller action being run using the currentRouteAction method:

  1. $action = Route::currentRouteAction();

Controller Middleware

Middleware may be specified on controller routes like so:

  1. Route::get('profile', [
  2. 'middleware' => 'auth',
  3. 'uses' => '[email protected]'
  4. ]);

Additionally, you may specify middleware within your controller's constructor:

  1. class UserController extends Controller {
  2. /**
  3. * Instantiate a new UserController instance.
  4. */
  5. public function __construct()
  6. {
  7. $this->middleware('auth');
  8. $this->middleware('log', ['only' => ['fooAction', 'barAction']]);
  9. $this->middleware('subscribed', ['except' => ['fooAction', 'barAction']]);
  10. }
  11. }

Implicit Controllers

Laravel allows you to easily define a single route to handle every action in a controller. First, define the route using the Route::controller method:

  1. Route::controller('users', 'UserController');

The controller method accepts two arguments. The first is the base URI the controller handles, while the second is the class name of the controller. Next, just add methods to your controller, prefixed with the HTTP verb they respond to:

  1. class UserController extends Controller {
  2. public function getIndex()
  3. {
  4. //
  5. }
  6. public function postProfile()
  7. {
  8. //
  9. }
  10. public function anyLogin()
  11. {
  12. //
  13. }
  14. }

The index methods will respond to the root URI handled by the controller, which, in this case, is users.

If your controller action contains multiple words, you may access the action using "dash" syntax in the URI. For example, the following controller action on our UserController would respond to the users/admin-profile URI:

  1. public function getAdminProfile() {}

Assigning Route Names

If you would like to "name" some of the routes on the controller, you may pass a third argument to the controller method:

  1. Route::controller('users', 'UserController', [
  2. 'anyLogin' => 'user.login',
  3. ]);

RESTful Resource Controllers

Resource controllers make it painless to build RESTful controllers around resources. For example, you may wish to create a controller that handles HTTP requests regarding "photos" stored by your application. Using the make:controller Artisan command, we can quickly create such a controller:

  1. php artisan make:controller PhotoController

Next, we register a resourceful route to the controller:

  1. Route::resource('photo', 'PhotoController');

This single route declaration creates multiple routes to handle a variety of RESTful actions on the photo resource. Likewise, the generated controller will already have methods stubbed for each of these actions, including notes informing you which URIs and verbs they handle.

Actions Handled By Resource Controller

VerbPathActionRoute Name
GET/photoindexphoto.index
GET/photo/createcreatephoto.create
POST/photostorephoto.store
GET/photo/{photo}showphoto.show
GET/photo/{photo}/editeditphoto.edit
PUT/PATCH/photo/{photo}updatephoto.update
DELETE/photo/{photo}destroyphoto.destroy

Customizing Resource Routes

Additionally, you may specify only a subset of actions to handle on the route:

  1. Route::resource('photo', 'PhotoController',
  2. ['only' => ['index', 'show']]);
  3. Route::resource('photo', 'PhotoController',
  4. ['except' => ['create', 'store', 'update', 'destroy']]);

By default, all resource controller actions have a route name; however, you can override these names by passing a names array with your options:

  1. Route::resource('photo', 'PhotoController',
  2. ['names' => ['create' => 'photo.build']]);

Handling Nested Resource Controllers

To "nest" resource controllers, use "dot" notation in your route declaration:

  1. Route::resource('photos.comments', 'PhotoCommentController');

This route will register a "nested" resource that may be accessed with URLs like the following: photos/{photos}/comments/{comments}.

  1. class PhotoCommentController extends Controller {
  2. /**
  3. * Show the specified photo comment.
  4. *
  5. * @param int $photoId
  6. * @param int $commentId
  7. * @return Response
  8. */
  9. public function show($photoId, $commentId)
  10. {
  11. //
  12. }
  13. }

Adding Additional Routes To Resource Controllers

If it becomes necessary to add additional routes to a resource controller beyond the default resource routes, you should define those routes before your call to Route::resource:

  1. Route::get('photos/popular', '[email protected]');
  2. Route::resource('photos', 'PhotoController');

Dependency Injection & Controllers

Constructor Injection

The Laravel service container is used to resolve all Laravel controllers. As a result, you are able to type-hint any dependencies your controller may need in its constructor:

  1. <?php namespace App\Http\Controllers;
  2. use Illuminate\Routing\Controller;
  3. use App\Repositories\UserRepository;
  4. class UserController extends Controller {
  5. /**
  6. * The user repository instance.
  7. */
  8. protected $users;
  9. /**
  10. * Create a new controller instance.
  11. *
  12. * @param UserRepository $users
  13. * @return void
  14. */
  15. public function __construct(UserRepository $users)
  16. {
  17. $this->users = $users;
  18. }
  19. }

Of course, you may also type-hint any Laravel contract. If the container can resolve it, you can type-hint it.

Method Injection

In addition to constructor injection, you may also type-hint dependencies on your controller's methods. For example, let's type-hint the Request instance on one of our methods:

  1. <?php namespace App\Http\Controllers;
  2. use Illuminate\Http\Request;
  3. use Illuminate\Routing\Controller;
  4. class UserController extends Controller {
  5. /**
  6. * Store a new user.
  7. *
  8. * @param Request $request
  9. * @return Response
  10. */
  11. public function store(Request $request)
  12. {
  13. $name = $request->input('name');
  14. //
  15. }
  16. }

If your controller method is also expecting input from a route parameter, simply list your route arguments after your other dependencies:

  1. <?php namespace App\Http\Controllers;
  2. use Illuminate\Http\Request;
  3. use Illuminate\Routing\Controller;
  4. class UserController extends Controller {
  5. /**
  6. * Update the specified user.
  7. *
  8. * @param Request $request
  9. * @param int $id
  10. * @return Response
  11. */
  12. public function update(Request $request, $id)
  13. {
  14. //
  15. }
  16. }

Note: Method injection is fully compatible with model binding. The container will intelligently determine which arguments are model bound and which arguments should be injected.

Route Caching

If your application is exclusively using controller routes, you may take advantage of Laravel's route cache. Using the route cache will drastically decrease the amount of time it take to register all of your application's routes. In some cases, your route registration may even be up to 100x faster! To generate a route cache, just execute the route:cache Artisan command:

  1. php artisan route:cache

That's all there is to it! Your cached routes file will now be used instead of your app/Http/routes.php file. Remember, if you add any new routes you will need to generate a fresh route cache. Because of this, you may wish to only run the route:cache command during your project's deployment.

To remove the cached routes file without generating a new cache, use the route:clear command:

  1. php artisan route:clear