Today We Learned: Laravel Single Action Controller Route Definitions
Intro to Single Action Controllers
In Laravel, the PHP framework we use to power our backend and API at Aryeo, route definitions typically reference a controller and method.
Route::get('/example-route', [ExampleController::class, 'method'])
However, at times, we come across one-off or complex actions. These actions don't fit well in an existing controller.
In these cases, we may choose create a separate controller for this action entirely. This controller does follow a full CRUDY implementation with index, show, edit, etc actions for a particular resource. Instead, this one controller encompasses just this single action.
Laravel refers to these as Single Action Controllers, and you can read about them in the framework's documentation here.
Route Definitions For Single Action Controllers
When defining a single action controller, we place a single __invoke
method on the controller. This gives the following structure:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class ExampleController extends Controller
{
public function __invoke()
{
// some action
}
}
Now with the implementation above, the following route definition logicially follows:
Route::get('/example-route', [ExampleController::class, '__invoke'])
However, today we learned the syntax is far cleaner. In face, you don't need to specify the method at all. The following route definition is also valid.
Route::get('/example-route', ExampleController::class)
Simply define invokable controller as such, and Laravel will resolve the __invoke
method as expected.