DEV Community

Arif Iqbal
Arif Iqbal

Posted on • Updated on

Invokable Controller in Laravel

Invokable controller in Laravel is one with only one method named __invoke() in it. It is useful when you need only one action for your controller and you are wondering what should I name it? Just name it __invoke() and it will be called (invoked) automatically when your route is hit.

When registering a route for your invokable controller, just pass the class name to it. You don't need to mention the method name. So, your route definition will look like

route::get('/home', HomepageController ::class);
Enter fullscreen mode Exit fullscreen mode

The Artisan command to create an invokable controller is

php artisan make:controller HomepageController --invokable
Enter fullscreen mode Exit fullscreen mode

The above command will generate a controller class like this

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class HomepageController extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {
        //
    }
}
Enter fullscreen mode Exit fullscreen mode

~ Happy Coding... :)

Discussion (0)