How do Invokable Controllers work in Laravel?

October 26, 2018

If a controller in Laravel has just one action then you simplify the controller by using the invoke() method. Create a controller with a invoke() method, then in your routes files you can just do the following:

<?php
Route::get('home','HomeController');

The controller code for HomeController could look something like this:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
    public function __invoke(Request $request)
    {
        return "Welcome to our homepage"
    }
}

Create the controller using this artisan command:

php artisan make:controller HomeController --invokable