Discover Laravel’s invokable controllers – a simpler, faster way to handle routes with just one method. Learn how to create and use them in this article.
What are invokable controllers?
Invokable controllers are a special type of controller in Laravel that allow you to define a single __invoke()
method to handle a route instead of defining multiple action methods.
In Laravel, a controller is a PHP class that handles HTTP requests and manages the application’s response. An invokable controller is a special type of controller in Laravel that allows you to define a single __invoke()
the method instead of defining multiple action methods like index()
, store()
, show()
etc.
Invokable controllers are supported in Laravel 5.3 or later versions. So, if you’re using a version of Laravel earlier than 5.3, you won’t be able to use invokable controllers.
Using an invokable controller, you can define a single action for a particular route, and Laravel will automatically call the __invoke()
 method when that route is requested. This can be useful when you have a simple action to perform, and you don’t want to create a separate method in your controller for it.
Read Also: Create Models in Node Js Sequelize ORM (updated 2024)
To create an invokable controller, you need to define a class with a __invoke()
method. Here’s an example:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ExampleController extends Controller
{
public function __invoke(Request $request)
{
return "Hello, World!";
}
}
In the example above, we have created an invokable controller called ExampleController
. It has a single __invoke()
method that returns the string “Hello, World!”.
To use this controller, you can define a route like this:
Route::get('/example', ExampleController::class);
In this route definition, we have specified the ExampleController
class as the controller for the /example
route. When a user visits this route, Laravel will automatically call the __invoke()
method on the ExampleController
class and return the “Hello, World!” string.
What Is The Use Of Invokable Controller In Laravel
In Laravel we are all used to using the default resource controllers which currently consist of these methods.
One controller for handling all the CRUD requests. Now this doesn’t look bad until you start defining those methods and very soon your controller becomes very fat and hard to manage and it becomes much worse if you are validating requests in the same controller instead of using separate FormRequest classes.
So instead of bloating your controllers with everything we can use a different approach where we will handle each request using its very own separate invokable controller.
So let’s say that we are handling the create and store requests for creating a post in our application. Creating a request will serve as a form to create a Post and store a request to add that Post in our database.
Read Also: How to Compare String in Python? [With Examples]
So let’s create two controllers one for handling create requests and another one for handling store requests. We can create our invokable controllers using the command:-
Notice that I have stored both controllers inside a PostManager directory. So all the controllers for managing the Posts will be stored in my PostManager directory.
Our controllers will look something like this:-
and…
Now what about this __invoke function? __invoke function is a type of magic method that will be called when you try to call an object as a function. So in simple words, this function makes our class called a function. And this is not just a Laravel-specific thing it is also available in core PHP. You will understand this more clearly when you reach the end of this article. Let’s have a look at our routes which would look like this:-
You can also write them like them.
Notice that we haven’t specified any method as we used to before in our routes like ‘CreateController@create’. So this is what __invokable will do for us it will automatically get called.
So now we can handle these requests in our controllers.
CreateController:-
In our CreateController we are just returning a view that contains a form for creating a Post.
StoreController:-
And this is what our StoreController will look like. It is just calling a method createPost which takes the form data and creates the post. As you can see it looks much cleaner than using a single controller for all the requests and is easy to manage too. And you might have noticed that we haven’t validated our request. So for validating requests you can still use the FormRequest classes or if you don’t like using them then you can also handle them in the same controller like this:-
Now you shouldn’t be adding too many methods in your invokable controllers and keep it as light as possible so if your validation logic gets quite big then I would still advise you to use the FormRequest classes. Anyway, give this approach a try in your next project and see if it helps you.
List of Laravel Controllers
Below are the controllers listed.
1. Basic Controllers
This is a simple illustration of the controller class. It’s worth noting that the ‘MyController‘ class is derived from the ‘Controller’ class, which serves as the foundation. The ‘Controller’ class includes utility methods such as ‘middleware,’ ‘dispatch,’ and ‘validate,’ which prove to be quite useful. You can assign middleware to the controller’s route or constructor using these methods.
User::foundOrLost($id)]);
}
}
The path to MyController may be designated as follows:
Route::get('user/{id}', 'MyController@show');
Assigning middleware in route files:
Route::get('profile', 'MyController@show')->middleware('auth');
Upon the matching of the route URI with a particular request, the ‘show’ method belonging to the ‘MyController’ class is triggered, and the parameters mentioned in the route are also assigned to the method.
Here are additional cherries just for you:
- It’s unnecessary to state the complete namespace of the controller since the ‘RouteServiceProvider’ automatically loads the route group containing the namespace. You only have to indicate the part of the name that comes after ‘App\Http\Controllers’.
- To define the single-action controller, just add one method named ‘__invoke’ to your controller.
Read Also: How To Trim Whitespace from a String in Python: Easy Methods
2. Resource Controllers
During the development of an application, CRUD operations (Create, Read, Update, Delete) are necessary. By utilizing Laravel resource controllers, creating a controller is all that is needed, as Laravel will handle the rest. The Laravel resource route will automatically assign the CRUD operation routes to the controller with just one line of code. All methods can be registered under a single route in the routes.php file.
To illustrate, imagine you need a controller to manage incoming HTTP requests related to stored ‘images’ in your application. Artisan command can efficiently help you accomplish this task. To create a similar controller, let’s examine the ‘make: controller’ Artisan command briefly.
php artisan make:controller ImageController --resource
Executing the aforementioned command will result in the creation of a controller located at app/Http/Controllers/ImageController.php. This controller will contain dedicated methods for every available resource operation.
It is now possible to specify a path that will manage multiple actions in the following manner:
Route::resource('images', 'ImageController');
By declaring this route, multiple routes can be created to handle a variety of actions. Each available action will have its specific method within the controller. Additionally, notes will be included to provide information about the URIs and HTTP verbs that are being managed.
To register multiple resource controllers simultaneously, use an array as demonstrated below.
Route::resources([
'images' => 'ImageController',
'posts' => 'PostController'
]);
3. Implicit Controllers
By utilizing these controllers, you can manage all actions with just one defined route. Initially, it is necessary to define a route by using Route:: controller, as shown here:
Route::controller('users', 'MyController');
The controller is receiving a pair of arguments.
- Base URI
- Controller’s class name
To proceed, simply include actions to ‘MyController’ with an HTTP verb preceding them.
class MyController extends Controller {
public function getIndex()
{
//
}
public function anyLogin()
{
//
}
public function postProfile()
{
//
}
}
The ‘index’ methods will be utilized for the ‘users’, which is the root/base URI managed by the Controller.
To access an action with multiple words, you can use a ‘dash’ in the URI. Take the controller action below as an instance.
public function getAdminProfile() {}
The action in MyController with the controller will handle the URI ‘users/admin-profile’.
4. Dependency Injection and Controllers
By utilizing Dependency Injection, it becomes simpler to both test and maintain your web applications.
The process of injecting dependencies via constructors.
Laravel handles the management of class dependencies and their resolution in controllers. In case your controller requires dependencies in the constructor, Laravel allows you to type-hint almost any of these dependencies. The service controller in Laravel will automatically resolve all dependencies and inject them into the controller instance.
users = $users;
}
}
Injecting methods.
Read Also: [Solve]: subprocess-exited-with-error in Python
In addition to injecting dependencies into the constructor, you can also utilize type-hinting to inject them into the methods of your controller. As an example, the controller’s method can receive an instance of Illuminate\Http\Request by injection.
name;
//
}
}
Features of Laravel Controllers
Listed below are some characteristics of the Laravel controller:
- Laravel’s support for MVC architecture allows for efficient development by enabling multiple users to work on different aspects of a project simultaneously. This is made possible by separating the business logic from the presentation logic, which eliminates the need for duplicating views when working with a single model.
- Laravel’s authentication system is already integrated, leaving you to focus on configuring the views, models, and controllers for other aspects.
- When developing an application, the most important aspect to consider is security. Laravel addresses this concern by offering built-in security measures.
- Artisan is a tool that assists developers by automating repetitive tasks. It can be utilized to simplify the creation of database structures, code, and migrations.
- Laravel’s template engine is both innovative and powerful, enabling developers to create dynamic web applications.
Conclusion:
In conclusion, an invokable controller in Laravel is a convenient way to define a single action for a particular route, without having to create multiple methods in your controller. It can make your code more concise and easier to read and can help you build applications more quickly.
Leave a Reply