Laravel Invokable Controllers: Simplify Route Handling for Faster Development - TechvBlogs

Laravel Invokable Controllers: Simplify Route Handling for Faster Development

Discover Laravel's invokable controllers - a simpler, faster way to handle routes with just one method. Learn how to create and use them in this article.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

1 year ago

TechvBlogs - Google News

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!";
    }
}

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);

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.

Comments (1)

Greg Greg 1 year ago

Given the example code, is it possible to reference the ExampleController as a route in a view or other controller? I understand that the routes.php entry connect the URL to the ExampleController but if it's not named, how do you specify it as a form handler, for example?

I've tried a variety of approaches but none of them work.

Comment


Note: All Input Fields are required.