1. Introduction
It is obviously unreasonable to put all the request processing logic in a single routes.php , and you might also want to use the Controller class organization to manage these behaviors. The controller can encapsulate the associated HTTP request into a class for processing. Usually the controller is stored in the app/Http/Controllers directory.
2. Basic control DeviceDefining the Controller
The following is an example of a basic controller class. All Laravel controllers should inherit from the Controller base class that comes with Laravel Controller , and the controller base class provides some handy ways to middleware add middleware-to-controller actions, for example:
<?phpnamespace app\http\controllers;use app\user;use App\http\controllers\controller;class UserController Extends controller{ /** * Show details for specified user * * @param int $id * @return Response */Public function Showprofile ($id) { return view (' User.profile ', [' user ' = ' user::findorfail ($id)]);} }
We can define a route that points to the controller action like this:
Route::get (' User/{id} ', ' [email protected] ');
Now, if a request matches the route URI above, UserController the showProfile method will be executed. Of course, routing parameters are also passed to this method.
Note: The controller is not necessarily inherited from the base class, but in that case it is not possible to use the convenient methods, such as middleware , validate and and dispatch so on.
Controllers & Namespaces
You should notice that we did not specify the full controller namespace when defining the controller route, but only the later ones App\Http\Controllers . By default, RouteServiceProvider a file is loaded in a routing group routes.php , and the routing group specifies the namespace in which the group is routed by the controller.
If you App\Http\Controllers choose to use the PHP namespace nesting or organization controller under the directory, you only need to use App\Http\Controllers the specified class name relative to the namespace. So, if your full controller class is App\Http\Controllers\Photos\AdminController , you can register the route like this:
Route::get (' foo ', ' photos\[email protected] ');
Single Action Controller
If you want to define a controller that handles only one action, you can define the method in this controller __invoke :
<?phpnamespace 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 you register a route for this single action controller, you do not need to specify a method:
Route::get (' User/{id} ', ' showprofile ');
3. Controller middleware
The middleware can be assigned to the controller route like this:
Route::get (' profile ', ' [email protected] ')->middleware (' auth ');
However, it is more convenient to put the middleware in the Controller constructor, and in the constructor of the controller middleware you can easily allocate the middleware to the controller. You can even qualify the middleware to apply the specified method to the Controller class:
Class Usercontroller extends controller{ /** * Instantiates a new Usercontroller instance * * @return void */ Public function __construct () { $this->middleware (' auth '); $this->middleware (' log ')->only (' index '); $this->middleware (' subscribed ')->except (' Store ');} }
Note: You can assign middleware to multiple controller actions, however, this means that your controller will become more and more bloated, in which case you need to consider splitting the controller into more, smaller controllers.
4. Resource Controller
Laravel's resource controller makes it painless to build RESTful controllers around resources, for example, you might want to create a controller in your app that handles HTTP requests for picture storage, and with the Artisan command make:controller , we can quickly create such a controller:
PHP Artisan Make:controller Photocontroller--resource
The Artisan command will generate a controller file app/Http/Controllers/PhotoController.php that contains the corresponding method for each resource operation.
Next, you can register a resource route for the controller:
Route::resource (' photos ', ' photocontroller ');
This route declaration contains multiple routes to handle the RESTful action of the picture resource, and accordingly, the controller generated by the Artisan has set up a corresponding processing method for these actions.
Actions handled by the resource controller
Method
Path
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
Forge a Form method
Because an HTML form cannot be initiated PUT , PATCH and DELETE requested, you need to add a hidden _method field to forge the HTTP request, the helper function method_field can help us do this:
{{Method_field (' PUT ')}}
Partial Resource Routing
When declaring a resource route, you can specify the subset of actions that the route handles:
Route::resource (' photo ', ' photocontroller ', [' only ' + = [' Index ', ' Show ']]); Route::resource (' photo ', ' photocontroller ', [' except ' = [' Create ', ' Store ', ' Update ', ' destroy ']);
Named Resource routing
By default, all resource controller actions have a route name, however, we can names override these default names by passing in the array:
Route::resource (' photo ', ' photocontroller ', [' names ' = [' Create ' = ' photo.build ']]);
named resource routing parameters
By default, Route::resource route parameters are created for resource routing based on the singular format of the resource name, which you can override by passing in an option array parameters . parametersshould be an associative array of resource names and parameter names:
Route::resource (' user ', ' adminusercontroller ', [' Parameters ' = [ ' user ' = ' admin_user ']]);
The example code above generates the following URL for the resource's show route:
/user/{admin_user}
Supplemental Resource Controller
If it is necessary to add additional routes to the resource controller outside of the default resource routing, Route::resource these routes should be defined prior to invocation; otherwise, resource routes defined by methods may inadvertently take precedence over supplemental additional routes:
Route::get (' photos/popular ', ' [email protected] '); Route::resource (' photos ', ' photocontroller ');
Note: Keep the controller's sole responsibility, if you find that the route that points to the controller action exceeds the default set of resource controller actions provided, consider splitting your controller into more, smaller controllers.
5, Dependent injection & controllerConstructor Injection
Laravel uses the service container to resolve all Laravel controllers, so any dependencies can be declared in the Controller's constructor, and these dependencies are automatically parsed and injected into the controller instance:
<?phpnamespace app\http\controllers;use Illuminate\routing\controller;use app\repositories\userrepository; Class Usercontroller extends controller{ /** * The user repository instance. */ protected $users; /** * Create a new controller instance * * @param userrepository $users * @return void */public function __ Construct (userrepository $users) { $this->users = $users; }}
Of course, you can also type hints for any Laravel contract, and if the container can parse it, you can type hints.
Method Injection
In addition to constructor injection, you can also make dependent type hints in the Controller's action methods, for example, we can type in a method to prompt an Illuminate\Http\Request instance:
<?phpnamespace App\http\controllers;use Illuminate\http\request;use Illuminate\routing\controller;class Usercontroller extends controller{ /** * Store new user * * @param Request $request * @return Response * /Public function store (Request $request ) {$name = $request->input (' name '); // }}
If the Controller method expects to enter a route parameter, simply place the route parameter after other dependencies, for example, if your route is defined as follows:
Route::p ut (' User/{id} ', ' [email protected] ');
You need to type hints Illuminate\Http\Request and access routing parameters by defining the Controller method as follows id :
<?phpnamespace App\http\controllers;use Illuminate\http\request;use Illuminate\routing\controller;class Usercontroller extends controller{ /** * Update specified user * * @param Request $request * @param int $id * @ return Response * @translator http://laravelacademy.org * /Public Function update (Request $request, $id) { // }}
6. Route Cache
Note: The route cache will not be used for closures-based routing. To use the route cache, the closure route must be converted to a controller route.
If your app is completely based on controller routing, you can use Laravel's route cache, which will greatly reduce the time spent registering all application routes, and in some cases, the speed of the route registration can even increase by 100 times times! To generate a route cache, simply execute the Artisan command route:cache :
PHP Artisan Route:cache
Once the run is complete, each request reads the route from the cache, remembering that if you add a new route you need to regenerate the route cache. Therefore, you need to run the command only during the project deployment phase route:cache .
To remove a cache route file, use the route:clear command:
PHP Artisan Route:clear
HTTP Layer--controller