Laravel Single Action Controllers
A single action controller is a controller with one __invoke method. It handles one route and nothing else.
Make one
Artisan adds the --invokable flag for a single action controller.
php artisan make:controller ShowBookController --invokableWrite the action
The class holds one method, and that method is the whole controller.
public function __invoke()
{
return 'Book: Dune';
}Point a route at the class
The route names the class only, because there is one method to call.
use App\Http\Controllers\ShowBookController;
Route::get('/books/1', ShowBookController::class);Example
use App\Http\Controllers\ShowBookController;
Route::get('/books/1', ShowBookController::class);
class ShowBookController extends Controller
{
public function __invoke()
{
return 'Book: Dune';
}
}Key points
- Single action controller: a controller class with only an __invoke method.
- __invoke: the method Laravel calls when a route points at the whole class.
- Use a single action controller for a route that needs its own class.
- Use the class name alone in the route, with no method name.
In this example, the route points at the ShowBookController class with no method name. The class holds one method called __invoke. That method returns the text for one book. A visit to /books/1 shows the text.
Note
A single action controller suits a one-off page, such as a welcome page.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
When should you use a single action controller?