Controllers

Introduction

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

Basic Controllers

Defining Controllers

Below is an example of a basic controller class. Note that the controller extends the base controller class included with Laravel. The base class provides a few convenience methods such as the middleware method, which may be used to attach middleware to controller actions:

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

You can define a route to this controller action like so:

  1. use App\Http\Controllers\UserController;
  2. Route::get('user/{id}', [UserController::class, 'show']);

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

{tip} Controllers are not required to extend a base class. However, you will not have access to convenience features such as the middleware, validate, and dispatch methods.

Single Action Controllers

If you would like to define a controller that only handles a single action, you may place a single __invoke method on the controller:

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

When registering routes for single action controllers, you do not need to specify a method:

  1. use App\Http\Controllers\ShowProfile;
  2. Route::get('user/{id}', ShowProfile::class);

You may generate an invokable controller by using the --invokable option of the make:controller Artisan command:

  1. php artisan make:controller ShowProfile --invokable

{tip} Controller stubs may be customized using stub publishing

Controller Middleware

Middleware may be assigned to the controller’s routes in your route files:

  1. Route::get('profile', [UserController::class, 'show'])->middleware('auth');

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’s action. 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 controller instance.
  5. *
  6. * @return void
  7. */
  8. public function __construct()
  9. {
  10. $this->middleware('auth');
  11. $this->middleware('log')->only('index');
  12. $this->middleware('subscribed')->except('store');
  13. }
  14. }

Controllers also allow you to register middleware using a Closure. This provides a convenient way to define a middleware for a single controller without defining an entire middleware class:

  1. $this->middleware(function ($request, $next) {
  2. // ...
  3. return $next($request);
  4. });

{tip} You may assign middleware to a subset of controller actions; however, it may indicate your controller is growing too large. Instead, consider breaking your controller into multiple, smaller controllers.

Resource Controllers

Laravel resource routing assigns the typical “CRUD” routes to a controller with a single line of code. For example, you may wish to create a controller that handles all HTTP requests for “photos” stored by your application. Using the make:controller Artisan command, we can quickly create such a controller:

  1. php artisan make:controller PhotoController --resource

This command will generate a controller 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('photos', PhotoController::class);

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

You may register many resource controllers at once by passing an array to the resources method:

  1. Route::resources([
  2. 'photos' => PhotoController::class,
  3. 'posts' => PostController::class,
  4. ]);

Actions Handled By Resource Controller

VerbURIActionRoute Name
GET/photosindexphotos.index
GET/photos/createcreatephotos.create
POST/photosstorephotos.store
GET/photos/{photo}showphotos.show
GET/photos/{photo}/editeditphotos.edit
PUT/PATCH/photos/{photo}updatephotos.update
DELETE/photos/{photo}destroyphotos.destroy

Specifying The Resource Model

If you are using route model binding and would like the resource controller’s methods to type-hint a model instance, you may use the --model option when generating the controller:

  1. php artisan make:controller PhotoController --resource --model=Photo

Partial Resource Routes

When declaring a resource route, you may specify a subset of actions the controller should handle instead of the full set of default actions:

  1. Route::resource('photos', PhotoController::class)->only([
  2. 'index', 'show'
  3. ]);
  4. Route::resource('photos', PhotoController::class)->except([
  5. 'create', 'store', 'update', 'destroy'
  6. ]);

API Resource Routes

When declaring resource routes that will be consumed by APIs, you will commonly want to exclude routes that present HTML templates such as create and edit. For convenience, you may use the apiResource method to automatically exclude these two routes:

  1. Route::apiResource('photos', PhotoController::class);

You may register many API resource controllers at once by passing an array to the apiResources method:

  1. Route::apiResources([
  2. 'photos' => PhotoController::class,
  3. 'posts' => PostController::class,
  4. ]);

To quickly generate an API resource controller that does not include the create or edit methods, use the --api switch when executing the make:controller command:

  1. php artisan make:controller API/PhotoController --api

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 the resource controllers, use “dot” notation in your route declaration:

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

This route will register a nested resource that may be accessed with URIs like the following:

  1. /photos/{photo}/comments/{comment}

Scoping Nested Resources

Laravel’s implicit model binding feature can automatically scope nested bindings such that the resolved child model is confirmed to belong to the parent model. By using the scoped method when defining your nested resource, you may enabling automatic scoping as well as instruct Laravel which field the child resource should be retrieved by:

  1. Route::resource('photos.comments', PhotoCommentController::class)->scoped([
  2. 'comment' => 'slug',
  3. ]);

This route will register a scoped nested resource that may be accessed with URIs like the following:

  1. /photos/{photo}/comments/{comment:slug}

Shallow Nesting

Often, it is not entirely necessary to have both the parent and the child IDs within a URI since the child ID is already a unique identifier. When using unique identifier such as auto-incrementing primary keys to identify your models in URI segments, you may choose to use “shallow nesting”:

  1. Route::resource('photos.comments', CommentController::class)->shallow();

The route definition above will define the following routes:

VerbURIActionRoute Name
GET/photos/{photo}/commentsindexphotos.comments.index
GET/photos/{photo}/comments/createcreatephotos.comments.create
POST/photos/{photo}/commentsstorephotos.comments.store
GET/comments/{comment}showcomments.show
GET/comments/{comment}/editeditcomments.edit
PUT/PATCH/comments/{comment}updatecomments.update
DELETE/comments/{comment}destroycomments.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('photos', PhotoController::class)->names([
  2. 'create' => 'photos.build'
  3. ]);

Naming Resource Route Parameters

By default, Route::resource will create the route parameters for your resource routes based on the “singularized” version of the resource name. You can easily override this on a per resource basis by using the parameters method. The array passed into the parameters method should be an associative array of resource names and parameter names:

  1. Route::resource('users', AdminUserController::class)->parameters([
  2. 'users' => 'admin_user'
  3. ]);

The example above generates the following URIs for the resource’s show route:

  1. /users/{admin_user}

Scoping Resource Routes

Sometimes, when implicitly binding multiple Eloquent models in resource route definitions, you may wish to scope the second Eloquent model such that it must be a child of the first Eloquent model. For example, consider this situation that retrieves a blog post by slug for a specific user:

  1. use App\Http\Controllers\PostsController;
  2. Route::resource('users.posts', PostsController::class)->scoped();

You may override the default model route keys by passing an array to the scoped method:

  1. use App\Http\Controllers\PostsController;
  2. Route::resource('users.posts', PostsController::class)->scoped([
  3. 'post' => 'slug',
  4. ]);

When using a custom keyed implicit binding as a nested route parameter, Laravel will automatically scope the query to retrieve the nested model by its parent using conventions to guess the relationship name on the parent. In this case, it will be assumed that the User model has a relationship named posts (the plural of the route parameter name) which can be used to retrieve the Post model.

Localizing Resource URIs

By default, Route::resource will create resource URIs using English verbs. If you need to localize the create and edit action verbs, you may use the Route::resourceVerbs method. This may be done in the boot method of your AppServiceProvider:

  1. use Illuminate\Support\Facades\Route;
  2. /**
  3. * Bootstrap any application services.
  4. *
  5. * @return void
  6. */
  7. public function boot()
  8. {
  9. Route::resourceVerbs([
  10. 'create' => 'crear',
  11. 'edit' => 'editar',
  12. ]);
  13. }

Once the verbs have been customized, a resource route registration such as Route::resource('fotos', 'PhotoController') will produce the following URIs:

  1. /fotos/crear
  2. /fotos/{foto}/editar

Supplementing Resource Controllers

If you need to add additional routes to a resource controller beyond the default set of 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', [PhotoController::class, 'popular']);
  2. Route::resource('photos', PhotoController::class);

{tip} Remember to keep your controllers focused. If you find yourself routinely needing methods outside of the typical set of resource actions, consider splitting your controller into two, smaller controllers.

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

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

You may also type-hint any Laravel contract. If the container can resolve it, you can type-hint it. Depending on your application, injecting your dependencies into your controller may provide better testability.

Method Injection

In addition to constructor injection, you may also type-hint dependencies on your controller’s methods. A common use-case for method injection is injecting the Illuminate\Http\Request instance into your controller methods:

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

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

  1. Route::put('user/{id}', [UserController::class, 'update']);

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

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

Route Caching

If your application is exclusively using controller based routes, you should 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

After running this command, your cached routes file will be loaded on every request. Remember, if you add any new routes you will need to generate a fresh route cache. Because of this, you should only run the route:cache command during your project’s deployment.

You may use the route:clear command to clear the route cache:

  1. php artisan route:clear