Controllers

Introduction

Instead of defining all of your request handling logic as closures in your route files, you may wish to organize this behavior using "controller" classes. Controllers can group related request handling logic into a single class. For example, a UserController class might handle all incoming requests related to users, including showing, creating, updating, and deleting users. By default, controllers are stored in the app/Http/Controllers directory.

Writing Controllers

Basic Controllers

Let's take a look at an example of a basic controller. Note that the controller extends the base controller class included with Laravel: App\Http\Controllers\Controller:

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

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

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

When an incoming request matches the specified route URI, the show method on the App\Http\Controllers\UserController class will be invoked and the route parameters will be passed to the method.

lightbulb

Controllers are not required to extend a base class. However, you will not have access to convenient features such as the middleware and authorize methods.

Single Action Controllers

If a controller action is particularly complex, you might find it convenient to dedicate an entire controller class to that single action. To accomplish this, you may define a single __invoke method within the controller:

1<?php
2 
3namespace App\Http\Controllers;
4 
5use App\Http\Controllers\Controller;
6use App\Models\User;
7 
8class ProvisionServer extends Controller
9{
10 /**
11 * Provision a new web server.
12 *
13 * @return \Illuminate\Http\Response
14 */
15 public function __invoke()
16 {
17 // ...
18 }
19}
1<?php
2 
3namespace App\Http\Controllers;
4 
5use App\Http\Controllers\Controller;
6use App\Models\User;
7 
8class ProvisionServer extends Controller
9{
10 /**
11 * Provision a new web server.
12 *
13 * @return \Illuminate\Http\Response
14 */
15 public function __invoke()
16 {
17 // ...
18 }
19}

When registering routes for single action controllers, you do not need to specify a controller method. Instead, you may simply pass the name of the controller to the router:

1use App\Http\Controllers\ProvisionServer;
2 
3Route::post('/server', ProvisionServer::class);
1use App\Http\Controllers\ProvisionServer;
2 
3Route::post('/server', ProvisionServer::class);

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

1php artisan make:controller ProvisionServer --invokable
1php artisan make:controller ProvisionServer --invokable
lightbulb

Controller stubs may be customized using stub publishing.

Controller Middleware

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

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

Or, you may find it convenient to specify middleware within your controller's constructor. Using the middleware method within your controller's constructor, you can assign middleware to the controller's actions:

1class 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}
1class 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 an inline middleware for a single controller without defining an entire middleware class:

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

Resource Controllers

If you think of each Eloquent model in your application as a "resource", it is typical to perform the same sets of actions against each resource in your application. For example, imagine your application contains a Photo model and a Movie model. It is likely that users can create, read, update, or delete these resources.

Because of this common use case, Laravel resource routing assigns the typical create, read, update, and delete ("CRUD") routes to a controller with a single line of code. To get started, we can use the make:controller Artisan command's --resource option to quickly create a controller to handle these actions:

1php artisan make:controller PhotoController --resource
1php 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 resource route that points to the controller:

1use App\Http\Controllers\PhotoController;
2 
3Route::resource('photos', PhotoController::class);
1use App\Http\Controllers\PhotoController;
2 
3Route::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. Remember, you can always get a quick overview of your application's routes by running the route:list Artisan command.

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

1Route::resources([
2 'photos' => PhotoController::class,
3 'posts' => PostController::class,
4]);
1Route::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

Customizing Missing Model Behavior

Typically, a 404 HTTP response will be generated if an implicitly bound resource model is not found. However, you may customize this behavior by calling the missing method when defining your resource route. The missing method accepts a closure that will be invoked if an implicitly bound model can not be found for any of the resource's routes:

1use App\Http\Controllers\PhotoController;
2use Illuminate\Http\Request;
3use Illuminate\Support\Facades\Redirect;
4 
5Route::resource('photos', PhotoController::class)
6 ->missing(function (Request $request) {
7 return Redirect::route('photos.index');
8 });
1use App\Http\Controllers\PhotoController;
2use Illuminate\Http\Request;
3use Illuminate\Support\Facades\Redirect;
4 
5Route::resource('photos', PhotoController::class)
6 ->missing(function (Request $request) {
7 return Redirect::route('photos.index');
8 });

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:

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

Generating Form Requests

You may provide the --requests option when generating a resource controller to instruct Artisan to generate form request classes for the controller's storage and update methods:

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

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:

1use App\Http\Controllers\PhotoController;
2 
3Route::resource('photos', PhotoController::class)->only([
4 'index', 'show'
5]);
6 
7Route::resource('photos', PhotoController::class)->except([
8 'create', 'store', 'update', 'destroy'
9]);
1use App\Http\Controllers\PhotoController;
2 
3Route::resource('photos', PhotoController::class)->only([
4 'index', 'show'
5]);
6 
7Route::resource('photos', PhotoController::class)->except([
8 'create', 'store', 'update', 'destroy'
9]);

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:

1use App\Http\Controllers\PhotoController;
2 
3Route::apiResource('photos', PhotoController::class);
1use App\Http\Controllers\PhotoController;
2 
3Route::apiResource('photos', PhotoController::class);

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

1use App\Http\Controllers\PhotoController;
2use App\Http\Controllers\PostController;
3 
4Route::apiResources([
5 'photos' => PhotoController::class,
6 'posts' => PostController::class,
7]);
1use App\Http\Controllers\PhotoController;
2use App\Http\Controllers\PostController;
3 
4Route::apiResources([
5 'photos' => PhotoController::class,
6 'posts' => PostController::class,
7]);

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:

1php artisan make:controller PhotoController --api
1php artisan make:controller 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, you may use "dot" notation in your route declaration:

1use App\Http\Controllers\PhotoCommentController;
2 
3Route::resource('photos.comments', PhotoCommentController::class);
1use App\Http\Controllers\PhotoCommentController;
2 
3Route::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}
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 enable automatic scoping as well as instruct Laravel which field the child resource should be retrieved by. For more information on how to accomplish this, please see the documentation on scoping resource routes.

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 identifiers such as auto-incrementing primary keys to identify your models in URI segments, you may choose to use "shallow nesting":

1use App\Http\Controllers\CommentController;
2 
3Route::resource('photos.comments', CommentController::class)->shallow();
1use App\Http\Controllers\CommentController;
2 
3Route::resource('photos.comments', CommentController::class)->shallow();

This route definition 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 desired route names:

1use App\Http\Controllers\PhotoController;
2 
3Route::resource('photos', PhotoController::class)->names([
4 'create' => 'photos.build'
5]);
1use App\Http\Controllers\PhotoController;
2 
3Route::resource('photos', PhotoController::class)->names([
4 'create' => 'photos.build'
5]);

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 using the parameters method. The array passed into the parameters method should be an associative array of resource names and parameter names:

1use App\Http\Controllers\AdminUserController;
2 
3Route::resource('users', AdminUserController::class)->parameters([
4 'users' => 'admin_user'
5]);
1use App\Http\Controllers\AdminUserController;
2 
3Route::resource('users', AdminUserController::class)->parameters([
4 'users' => 'admin_user'
5]);

The example above generates the following URI for the resource's show route:

1/users/{admin_user}
1/users/{admin_user}

Scoping Resource Routes

Laravel's scoped 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 enable automatic scoping as well as instruct Laravel which field the child resource should be retrieved by:

1use App\Http\Controllers\PhotoCommentController;
2 
3Route::resource('photos.comments', PhotoCommentController::class)->scoped([
4 'comment' => 'slug',
5]);
1use App\Http\Controllers\PhotoCommentController;
2 
3Route::resource('photos.comments', PhotoCommentController::class)->scoped([
4 'comment' => 'slug',
5]);

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

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

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 Photo model has a relationship named comments (the plural of the route parameter name) which can be used to retrieve the Comment 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 at the beginning of the boot method within your application's App\Providers\RouteServiceProvider:

1/**
2 * Define your route model bindings, pattern filters, etc.
3 *
4 * @return void
5 */
6public function boot()
7{
8 Route::resourceVerbs([
9 'create' => 'crear',
10 'edit' => 'editar',
11 ]);
12 
13 // ...
14}
1/**
2 * Define your route model bindings, pattern filters, etc.
3 *
4 * @return void
5 */
6public function boot()
7{
8 Route::resourceVerbs([
9 'create' => 'crear',
10 'edit' => 'editar',
11 ]);
12 
13 // ...
14}

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

1/fotos/crear
2 
3/fotos/{foto}/editar
1/fotos/crear
2 
3/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 the Route::resource method; otherwise, the routes defined by the resource method may unintentionally take precedence over your supplemental routes:

1use App\Http\Controller\PhotoController;
2 
3Route::get('/photos/popular', [PhotoController::class, 'popular']);
4Route::resource('photos', PhotoController::class);
1use App\Http\Controller\PhotoController;
2 
3Route::get('/photos/popular', [PhotoController::class, 'popular']);
4Route::resource('photos', PhotoController::class);
lightbulb

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

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

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:

1use App\Http\Controllers\UserController;
2 
3Route::put('/user/{id}', [UserController::class, 'update']);
1use App\Http\Controllers\UserController;
2 
3Route::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 
3namespace App\Http\Controllers;
4 
5use Illuminate\Http\Request;
6 
7class UserController extends Controller
8{
9 /**
10 * Update the given user.
11 *
12 * @param \Illuminate\Http\Request $request
13 * @param string $id
14 * @return \Illuminate\Http\Response
15 */
16 public function update(Request $request, $id)
17 {
18 //
19 }
20}
1<?php
2 
3namespace App\Http\Controllers;
4 
5use Illuminate\Http\Request;
6 
7class UserController extends Controller
8{
9 /**
10 * Update the given user.
11 *
12 * @param \Illuminate\Http\Request $request
13 * @param string $id
14 * @return \Illuminate\Http\Response
15 */
16 public function update(Request $request, $id)
17 {
18 //
19 }
20}

Comments

No Comments Yet

“Laravel” is a Trademark of Taylor Otwell.
The source documentation is released under MIT license. See laravel/docs on GitHub for details.
The translated documentations are released under MIT license. See cornch/laravel-docs-l10n on GitHub for details.