We can also assign the middleware to the controller's routes within your route files.
There are various ways of assigning the middleware to the controller:
Assigning the middleware to the controller in the web.php file.
We can assign the middleware to the controller in the web.php file. Following are the steps required to assign the middleware:
Step 1: First, we create a controller. We already have created the controller named as PostController in the previous topic.
Step 2: Now, we create the middleware, which we want to assign to the PostController. We use the following command to create the middleware:
The above command creates the middleware named Check.
Step 3: Open the Check.php file created in laravelproject/app/http/Middleware directory.
Step 4: Now, we have to add the path of the middleware Check.php in kernel.php file.
In the above code, the highlighted statement adds the path of the middleware, i.e., Check.
Step 5: Add the following code in the web.php file to assign the middleware to the PostController.
The above code assigns the middleware, i.e., check to the PostController.
Step 6: Enter the URL http://localhost/laravelproject/public/posts to the web browser, then the output would be:
Using the Controller constructor
We can also use the controller constructor to assign the middleware. It is more convenient as it restricts the middleware to only specific methods on a controller class.
The following are the steps required to assign the middleware using the Controller constructor:
The above code assigns the middleware to only show() method.
After adding the above code in PostController, structure of postController would look like:
If we access the URL http://localhost/laravelproject/public/posts, then the output would be:
The above output shows that when we access the create() method, the middleware Check.php file(middleware) will not be executed.
If we change the code of web.php file, and the code is:
In the above case, we are accessing the show() method of the PostController.php file, so it is executing the Check.php file(middleware) also.
Controllers also allows you to register the routes using the middleware closure. It allows the application to define the middleware for a single controller without defining the middleware class separately.
Syntax of Middleware Closure