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. All Laravel controllers should extend the base controller class included with the default Laravel installation:

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

We can route to the controller action like so:

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

Now, when a request matches the specified route URI, the showProfile method on the UserController class will be executed. Of course, the route parameters will also be passed to the method.

Controllers & Namespaces

It is very important to note that we did not need to specify the full controller namespace when defining the controller route. We only defined 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

You may also use the route helper to generate a URL to a named controller route:

  1. $url = route('name');

You may also use the action helper method to generate a URL using the controller's class and method names. Again, we only need to specify the part of the controller class name that comes after the base App\Http\Controllers namespace:

  1. $url = action('[email protected]');

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

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

Controller Middleware

Middleware may be assigned to the controller's routes like so:

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

However, it is more convenient to specify middleware within your controller's constructor. Using the middleware method from your controller's constructor, you may easily assign middleware to the controller. You may even restrict the middleware to only certain methods on the controller class:

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

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

The Artisan command will generate a controller file at app/Http/Controllers/PhotoController.php. The controller will contain a method for each of the available resource operations.

Next, you may 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

Partial Resource Routes

When declaring a resource route, you may specify 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']]);

Naming Resource Routes

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']]);

Nested Resources

Sometimes you may need to define routes to a "nested" resource. For example, a photo resource may have multiple "comments" that may be attached to the photo. 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. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Controllers\Controller;
  4. class PhotoCommentController extends Controller
  5. {
  6. /**
  7. * Show the specified photo comment.
  8. *
  9. * @param int $photoId
  10. * @param int $commentId
  11. * @return Response
  12. */
  13. public function show($photoId, $commentId)
  14. {
  15. //
  16. }
  17. }

Supplementing 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; otherwise, the routes defined by the resource method may unintentionally take precedence over your supplemental routes:

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

Implicit Controllers

Laravel allows you to easily define a single route to handle every action in a controller class. First, define the route using the Route::controller method. 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:

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

Next, just add methods to your controller. The method names should begin with the HTTP verb they respond to followed by the title case version of the URI:

  1. <?php
  2. namespace App\Http\Controllers;
  3. class UserController extends Controller
  4. {
  5. /**
  6. * Responds to requests to GET /users
  7. */
  8. public function getIndex()
  9. {
  10. //
  11. }
  12. /**
  13. * Responds to requests to GET /users/show/1
  14. */
  15. public function getShow($id)
  16. {
  17. //
  18. }
  19. /**
  20. * Responds to requests to GET /users/admin-profile
  21. */
  22. public function getAdminProfile()
  23. {
  24. //
  25. }
  26. /**
  27. * Responds to requests to POST /users/profile
  28. */
  29. public function postProfile()
  30. {
  31. //
  32. }
  33. }

As you can see in the example above, index methods will respond to the root URI handled by the controller, which, in this case, is users.

Assigning Route Names

If you would like to name some of the routes on the controller, you may pass an array of names as the third argument to the controller method:

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

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. The dependencies will automatically be resolved and injected into the controller instance:

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

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 action methods. For example, let's type-hint the Illuminate\Http\Request instance on one of our methods:

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

If your controller method is also expecting input from a route parameter, simply list your route arguments after your other dependencies. For example, if your route is defined like so:

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

You may still type-hint the Illuminate\Http\Request and access your route parameter id by defining your controller method like the following:

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

Route Caching

Note: Route caching does not work with Closure based routes. To use route caching, you must convert any Closure routes to use controller classes.

If your application is exclusively using controller based routes, you may take advantage of Laravel's route cache. Using the route cache will drastically decrease the amount of time it takes 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