Hi Developers,
Lets see about the invokable controller, If any of the controller function is more complex it will be more convenient to dedicate the entire controller class to do a single action. This can be achieved by using the __invoke method in Laravel. By declaring the controller as a invokable controller it can be only use to do the specific functions only, Lets see how its done.
Creating the invokable Controller : Creating a invokable controller is similar as of creating normal controller. It is done by adding --invokable in the Artisan command.
php artisan make:controller ProvisionServer --invokable
While declaring the route for the invokable controller we don't have to determine the class name since invokable controller it dedicated to perform a single function only.
web.php
use App\Http\Controllers\ProvisionServer;
Route::get('/server', ProvisionServer::class);
Defining the invokable controller : The controller is declared by adding the __invoke()
<?php
namespace App\Http\Controllers;
class ProvisionServer extends Controller
{
/**
* Provision a new web server.
*/
public function __invoke()
{
// ...
}
}
Running the Laravel Project
php artisan serve
Calling the Controller via Route
http://localhost:8000/server
We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.
Be the first to know about releases and tutorial news and solutions.
We care about your data in our privacy policy.
ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.
Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides