DEV Community

Cover image for Laravel Invokable Controllers: Simplify Route Handling for Faster Development
Suresh Ramani
Suresh Ramani

Posted on • Originally published at techvblogs.com

Laravel Invokable Controllers: Simplify Route Handling for Faster Development

What are invokable controllers?

Invokable controllers are a special type of controller in Laravel that allow you to define a single __invoke() method to handle a route instead of defining multiple action methods.

In Laravel, a controller is a PHP class that handles HTTP requests and manages the application's response. An invokable controller is a special type of controller in Laravel that allows you to define a single __invoke() the method instead of defining multiple action methods like index(), store(), show() etc.

Invokable controllers are supported in Laravel 5.3 or later versions. So, if you're using a version of Laravel earlier than 5.3, you won't be able to use invokable controllers.

Using an invokable controller, you can define a single action for a particular route, and Laravel will automatically call the __invoke() method when that route is requested. This can be useful when you have a simple action to perform, and you don't want to create a separate method in your controller for it.

To create an invokable controller, you need to define a class with a __invoke() method. Here's an example:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ExampleController extends Controller
{
    public function __invoke(Request $request)
    {
        return "Hello, World!";
    }
}
Enter fullscreen mode Exit fullscreen mode

In the example above, we have created an invokable controller called ExampleController. It has a single __invoke() method that returns the string "Hello, World!".

To use this controller, you can define a route like this:

Route::get('/example', ExampleController::class);
Enter fullscreen mode Exit fullscreen mode

In this route definition, we have specified the ExampleController class as the controller for the /example route. When a user visits this route, Laravel will automatically call the __invoke() method on the ExampleController class and return the "Hello, World!" string.

In conclusion, an invokable controller in Laravel is a convenient way to define a single action for a particular route, without having to create multiple methods in your controller. It can make your code more concise and easier to read, and can help you build applications more quickly.

Top comments (0)