How To Create invokable Controller In Laravel

  Oct 2023
  ITSolutionsGuides
  Category: Laravel
How To Create invokable Controller In Laravel

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.

Let's Start Coding

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

Let's Start Coding

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);

Let's Start Coding

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()
    {
        // ...
    }
}

Let's Start Coding

Running the Laravel Project

php artisan serve

Let's Start Coding

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.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

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.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides