Laravel for Beginners – Learn to Build Full-Stack Web Apps

Loading video...

Single Action Controllers

Controllers

Single Action Controllers

If the controller grows and becomes very large, it’s recommended practice to split it into multiple other controllers or create Single Action Controllers.

Generate Single Action Controller

Open terminal and execute the following artisan command

php artisan make:controller ShowCarController --invokable

ShowCarController.php class was generated in app/Http/Controllers folder. This is the default content of the just generated invokable controller in Laravel 11.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ShowCarController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request)
    {
        //
    }
}

__invoke method is the method that will be executed when route will be matched. This is how we associate the controller to a route.

Route::get("/car", \App\Http\Controllers\ShowCarController::class);

Note that we only provided controller class name when defining route for /car. We don’t need to provide methods for Single Action Controllers.

A regular controller with regular methods can also have __invoke method. For example we can modify our existing CarController and add __invoke method

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CarController extends Controller
{
    public function __invoke(Request $request)
    {
        return "From __invoke";
    }

    public function index()
    {
        return "Index method from CarController";
    }
}

In routes we can use CarController in the following way.

Route::get("/car", [CarController::class, 'index']);
Route::get("/car/invokable", CarController::class);

For /car route we use regular method of the controller, but for /car/invokable route we pass the entire controller class name and Laravel’s router will execute __invoke method behind.

Discussion

Sign in to join the discussion.

No comments yet. Be the first to start the discussion!