Trusted answers to developer questions

What is a single-action controller in Laravel?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

widget

What is a single-action controller in Laravel?

If you need to structure a specific module that has one action, then the single-action controller comes into play.

Firstly, define a single __invoke method in your controller:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;

class ControllerName extends Controller
{
    
    public function __invoke()
    {
        // ... your logic goes here
    }
}

Normally while registering routes for a controller, we pass the method like this:

Route::post('/server', 'ControllerName@index');

Depending on the method of handling the request in the controller, you use the name of the controller class for a single-action controller:

use App\Http\Controllers\ProvisionServer;

Route::post('/server', ControllerName::class);

In order to create a single-action controller, you run the artisan command below:

php artisan make:controller ControllerName --invokable

RELATED TAGS

single action controller
controller
laravel

CONTRIBUTOR

Chinweuba Elijah Azubuike
Did you find this helpful?