Routing controllers allow you to create the controller classes with methods used to handle the requests.
Now, we will understand the routing controllers through an example.
Step 1: First, we need to create a controller. We already created the controller named as 'PostController' in the previous topic.
Step 2: Open the web.php file and write the following code:
In the above code, '/post' is the URL that we want to access, and PostController is the name of the controller. The 'index' is the name of the method available in the PostController.php file, and @index indicates that the index() method should be hit when we access the '/post' url.
Step 3: Add the code which is shown below as highlighted:
Step 4: Enter the URL in the browser, i.e., localhost/laravelproject/public/host, then the output would be shown as below:
Till now, we have observed how we can access the Controller. Now, we will see that how to pass the data to the Controller class.
Passing data to the Controller
Let's understand through an example of how we can pass the data to the Controller:
Step 1: Open the web.php file and add the following code:
The above code contains the 'id' parameter in the '/post' url.
Step 2: Edit the PostController.php file.
In the above case, we have updated the index() method. We have passed the 'id' parameter in the index() method.
Step 3: Enter the URL 'localhost/laravelproject/post/100' into the web browser, then the output would be shown as below:
Controllers and Namespaces
When we specify the controller class in Route::get() method, then we do not need to specify the full controller namespace. As RouteServiceProvider loads all the route files that contain the namespace, we just need to specify the class name that comes after the App/Http/Controllers portion of the namespace.
If the full controller class is App/Http/Controllers/Post/PostController, then we can register the routes of the Controller as given below:
Single Action Controllers
If we want to use the single method in a controller, then we can use the single __invoke() method on the controller.
When we create the controller by using the command php artisan:make controller PostController then the structure of the PostController file would be:
Now, we add the code of __invoke() function in a PostController class:
In the end, we add the code in the web.php file, which is responsible for handling the actions.
The above code hits the __invoke() method of a PostController class. This concludes that we do not need to write the @invoke method for accessing the single action controllers.
When we enter the URL 'localhost/laravelproject/public/post/67', then the output would be:
If no action is specified, i.e., we forget to write the __invoke() method, then the UnexpectedValueExpression is thrown.
Suppose we remove the __invoke() method from the PostController class then the output would be: