MasterPHP.in
Try Compiler →
Laravel Tutorial

Single Action (Invokable) Controllers in Laravel


Your invoice app now has a neat resource controller with the seven standard methods. Then new requirements arrive. The owner wants a summary page with total sales and GST. The accountant wants a button that emails a payment reminder. Razorpay needs a callback URL that it can call after a payment.

None of these fit the seven standard actions. The easy move is to add summary(), sendReminder() and razorpayCallback() to InvoiceController. A month later that controller has fifteen methods, half of them unrelated, and you scroll through it just to find one.

Laravel has a cleaner option for actions like these. A single action controller is a class that does exactly one job. In this lesson you will create one, connect it to a route without naming a method, and learn when this style is the right choice.

 

The Problem with One-Off Actions

Here is what the controller starts to look like when every extra job is squeezed into it:

class InvoiceController extends Controller
{
    public function index() { /* ... */ }
    public function show(int $invoice) { /* ... */ }
    // ... the other five resource methods ...

    public function summary() { /* totals and GST */ }
    public function sendReminder(int $invoice) { /* email */ }
    public function razorpayCallback() { /* payment webhook */ }
    public function exportCsv() { /* download */ }
}

This has real costs:

  • The class mixes CRUD with unrelated jobs, so its purpose is no longer clear
  • A payment webhook has nothing to do with listing invoices, yet it lives in the same file
  • Method names like razorpayCallback have to carry extra context that a class name could carry for free
  • Several developers editing one large file means more merge conflicts

 

What Is a Single Action Controller?

A single action controller has only one public method, and that method is always named __invoke. The class represents one action, and the class name tells you what that action is.

Before using it in Laravel, it helps to see what __invoke means in plain PHP. It is a special method that lets you call an object as if it were a function:

class Greeting
{
    public function __invoke(string $name)
    {
        return "Namaste, {$name}";
    }
}

$greet = new Greeting();
echo $greet('Asha');   // Namaste, Asha

The object $greet is used with round brackets, and PHP runs __invoke. Laravel uses the same idea. When a route points to an invokable controller, Laravel creates the object and calls it, so there is no need to name a method.

 

Creating an Invokable Controller

Add the --invokable option to make:controller. Let’s create the invoice summary controller:

php artisan make:controller InvoiceSummary --invokable

Laravel creates app/Http/Controllers/InvoiceSummary.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class InvoiceSummary extends Controller
{
    public function __invoke(Request $request)
    {
        //
    }
}

Compare this with the resource controller from the last lesson. There are no index or show methods here, only __invoke. The Request $request argument is added by default. If you do not need it, you can delete it, and that is perfectly fine. You will learn what the request object holds in the Request Object lesson in the next chapter.

 

Writing the Action

Fill in the method. There is no database yet, so we will keep using sample amounts in rupees:

<?php

namespace App\Http\Controllers;

class InvoiceSummary extends Controller
{
    public function __invoke()
    {
        $amounts = [12500, 8400, 21000];

        $subtotal = array_sum($amounts);
        $gst = $subtotal * 0.18;

        return [
            'invoices' => count($amounts),
            'subtotal' => $subtotal,
            'gst'      => $gst,
            'total'    => $subtotal + $gst,
        ];
    }
}

This class does one thing. Anyone opening the file sees the whole feature at once, with no unrelated code around it. In a later chapter, the sample array will be replaced by a real database query.

 

Routing to an Invokable Controller

This is where invokable controllers are most convenient. In a normal controller you pass an array with the class and a method name. For an invokable controller you pass only the class:

use App\Http\Controllers\InvoiceController;
use App\Http\Controllers\InvoiceSummary;

// Normal controller: class and method
Route::get('/invoices', [InvoiceController::class, 'index']);

// Invokable controller: just the class
Route::get('/invoices/summary', InvoiceSummary::class)
    ->name('invoices.summary');

Route::resource('invoices', InvoiceController::class);

Laravel looks at the class, finds __invoke and runs it. Everything you learned about routes still applies, so you can add ->name(), constraints and the other options in the same way.

Notice that the summary route is placed above Route::resource(). As you saw in the last lesson, if the resource is registered first, the {invoice} route will catch the word summary before your route gets a chance.

Visit http://localhost:8000/invoices/summary and you will see the totals as JSON.

 

Route Parameters

Route parameters work exactly as they do in other controllers. The values arrive as arguments of __invoke:

php artisan make:controller SendInvoiceReminder --invokable

Route::post('/invoices/{invoice}/remind', SendInvoiceReminder::class)
    ->whereNumber('invoice')
    ->name('invoices.remind');

public function __invoke(int $invoice)
{
    return "Reminder sent for invoice {$invoice}";
}

This route uses POST because sending a reminder changes something in the real world, and a GET link should never do that. You will build proper forms and buttons for POST requests in the Forms & Validation chapter.

 

Example: A Razorpay Callback

Payment callbacks are a perfect fit for this style. The job is small, specific and unrelated to the rest of your app. In the Named Routes lesson you built a callback route with a closure. Here is the same idea as an invokable controller:

php artisan make:controller Payments/RazorpayCallback --invokable


<?php

namespace App\Http\Controllers\Payments;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class RazorpayCallback extends Controller
{
    public function __invoke(Request $request)
    {
        // Later: verify the signature and mark the invoice as paid
        return 'Payment received';
    }
}


use App\Http\Controllers\Payments\RazorpayCallback;

Route::post('/payments/razorpay/callback', RazorpayCallback::class)
    ->name('payments.razorpay.callback');

The name payments.razorpay.callback stays the same as before, so any route() call you wrote earlier keeps working. Because the controller is inside a subfolder, Laravel puts it in the App\Http\Controllers\Payments namespace, and you must import the base Controller class yourself, as shown above.

 

Naming Single Action Controllers

A resource controller is named after a thing, like InvoiceController. A single action controller is named after the action, so the name should read like a short instruction:

InvoiceSummary
SendInvoiceReminder
DownloadInvoicePdf
RazorpayCallback

Adding the word Controller at the end is allowed and some teams do it, but it is not required. The important rule is that the name should make the purpose obvious without opening the file. If you keep many of these classes, group them in subfolders such as Invoices/ or Payments/.

 

When to Use a Single Action Controller

Choose this style when a controller has one clear job that does not fit the seven resource methods. Good examples are:

  • Webhooks and payment callbacks
  • Dashboard or summary pages
  • File downloads and exports
  • Buttons that trigger one action, like sending a reminder
  • Small endpoints such as a health check

Do not use it for normal CRUD. A resource controller is the better tool when you need list, show, create, edit and delete for the same thing. If you find that an invokable class needs a second public method, it probably wants to be a regular controller instead.

An invokable controller is not special in any other way. It is still a controller, it still extends Controller, and it can still use private helper methods. Features like dependency injection and middleware work with it too, and you will see them in the next lesson and in the Middleware chapter.

 

Common Mistakes

Mistake 1: Misspelling __invoke

The method name needs two underscores at the start. Writing _invoke or invoke means the class has no callable method, and Laravel throws:

UnexpectedValueException: Invalid route action: [App\Http\Controllers\InvoiceSummary].

Check the method name carefully, because this error does not tell you what is wrong with the spelling.

 

Mistake 2: Expecting Another Method to Run

class InvoiceSummary extends Controller
{
    public function __invoke() { /* ... */ }

    public function monthly() { /* never called by the route */ }
}

A route that points to InvoiceSummary::class always runs __invoke. The monthly() method will never run from that route. If you need two actions, create two single action controllers or use a regular controller.

 

Mistake 3: Forgetting the Import

Route::get('/invoices/summary', InvoiceSummary::class);

Without the use App\Http\Controllers\InvoiceSummary; line, PHP cannot find the class, and you see:

Illuminate\Contracts\Container\BindingResolutionException: Target class [InvoiceSummary] does not exist.

This is the same error you met in the first controller lesson, and the fix is the same.

 

Mistake 4: Registering the Route After Route::resource()

If /invoices/summary comes after Route::resource('invoices', ...), the resource route catches it first and runs show() with the text summary:

TypeError: App\Http\Controllers\InvoiceController::show(): Argument #1 ($invoice) must be of type int, string given

Always place specific routes above the resource line.

 

Mistake 5: 419 Page Expired on a Callback

An outside service like Razorpay sends a POST request to your route, but it does not have your CSRF token. Laravel rejects it and the response says 419 | Page Expired. Callback and webhook routes must be excluded from CSRF checking, which is configured in bootstrap/app.php. You will learn how in the Middleware lessons.

 

Mistake 6: Using This Style for Everything

Some developers turn the whole app into single action classes, and end up with fifty tiny files for one resource. That is hard to navigate. Use resource controllers for related CRUD actions, and invokable ones for the exceptions.

 

Quick Summary

  • A single action controller has one public method, named __invoke, and does one job.
  • __invoke is a PHP feature that lets an object be called like a function.
  • Create one with php artisan make:controller InvoiceSummary --invokable.
  • Route to it with only the class: Route::get('/invoices/summary', InvoiceSummary::class).
  • Names, constraints and route parameters work as usual.
  • Name the class after the action, such as SendInvoiceReminder or RazorpayCallback.
  • Good uses include webhooks, summaries, exports and one-click actions.
  • Use a resource controller for full CRUD, and an invokable controller for one-off jobs.
  • Place your specific routes above Route::resource() so they are matched first.
  • Outside callbacks like Razorpay’s need a CSRF exception.

 

What’s Next

You have now seen the three main ways to write a controller: a plain one, a resource one and a single action one. But controllers rarely work alone. They need other classes, such as a payment service or a mail sender, and Laravel can hand these to your controller automatically. In the next lesson, Dependency Injection in Controllers, you will learn how to ask Laravel for the objects your controller needs.

Frequently Asked Questions

It is a special method that PHP runs when you use an object like a function, with round brackets after its name. Laravel uses it for single action controllers, so the route can call the class directly without naming a method. The two underscores at the start are required.
It can have private helper methods that __invoke uses internally. But a route will only ever call __invoke, so a second public method would never be reached through a route. If you need more than one public action, a regular controller is the better choice.
No. The difference in speed is too small to matter. The reason to use one is organization, since a class with one clear job is easier to find, read and change.
Yes. Route parameters arrive as arguments of the __invoke method, and you can chain name, whereNumber and other route options in the same way as before. The only difference is that you pass the class name alone instead of an array.
Ask whether the actions belong to one thing that you list, show, create, edit and delete. If yes, use a resource controller. If the job stands alone, like a payment callback or a report download, use a single action controller.

Share this tutorial