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:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* Show the profile for the given user.
*
* @param int $id
* @return Response
*/
public function show($id)
{
return view('user.profile', ['user' => User::findOrFail($id)]);
}
}
You can define a route to this controller action like so:
Route::get('user/{id}', 'UserController@show');
Now, when a request matches the specified route URI, the show
method on the UserController
class will be executed. Of course, the route parameters will also be passed to the method.
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.
Controllers & Namespaces
It is very important to note that we did not need to specify the full controller namespace when defining the controller route. Since the RouteServiceProvider
loads your route files within a route group that contains the namespace, we only specified the portion of the class name that comes after the App\Http\Controllers
portion of the namespace.
If you choose to nest your controllers deeper into the App\Http\Controllers
directory, 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 should register routes to the controller like so:
Route::get('foo', 'Photos\AdminController@method');
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:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class ShowProfile extends Controller
{
/**
* Show the profile for the given user.
*
* @param int $id
* @return Response
*/
public function __invoke($id)
{
return view('user.profile', ['user' => User::findOrFail($id)]);
}
}
When registering routes for single action controllers, you do not need to specify a method:
Route::get('user/{id}', 'ShowProfile');
You may generate an invokable controller by using the --invokable
option of the make:controller
Artisan command:
php artisan make:controller ShowProfile --invokable
Controller Middleware
Middleware may be assigned to the controller's routes in your route files:
Route::get('profile', 'UserController@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:
class UserController extends Controller
{
/**
* Instantiate a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('log')->only('index');
$this->middleware('subscribed')->except('store');
}
}
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:
$this->middleware(function ($request, $next) {
// ...
return $next($request);
});
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:
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:
Route::resource('photos', 'PhotoController');
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:
Route::resources([
'photos' => 'PhotoController',
'posts' => 'PostController'
]);
Actions Handled By Resource Controller
Verb | URI | Action | Route Name |
---|---|---|---|
GET | /photos | index | photos.index |
GET | /photos/create | create | photos.create |
POST | /photos | store | photos.store |
GET | /photos/{photo} | show | photos.show |
GET | /photos/{photo}/edit | edit | photos.edit |
PUT/PATCH | /photos/{photo} | update | photos.update |
DELETE | /photos/{photo} | destroy | photos.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:
php artisan make:controller PhotoController --resource --model=Photo