How to Use Single Action Controller in Laravel
In Laravel, a
single action controller is a controller class with only one method called __invoke. You create it by defining the __invoke method and then route to the controller class directly without specifying a method.Syntax
A single action controller in Laravel uses the special __invoke method. This method is called automatically when the controller is used in a route.
- __invoke(): The only method in the controller that handles the request.
- Route: You point the route directly to the controller class without specifying a method.
php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ExampleController { public function __invoke(Request $request) { // Handle the request here } }
Example
This example shows a single action controller that returns a simple greeting message when accessed.
php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class GreetingController { public function __invoke(Request $request) { return response('Hello from single action controller!'); } } // In routes/web.php use App\Http\Controllers\GreetingController; Route::get('/greet', GreetingController::class);
Output
Hello from single action controller!
Common Pitfalls
Common mistakes when using single action controllers include:
- Forgetting to define the
__invokemethod, which causes errors because Laravel expects it. - Trying to specify a method in the route when using a single action controller; you should only provide the controller class.
- Not importing the controller class correctly in the routes file.
php
<?php // Wrong: specifying method in route Route::get('/greet', [GreetingController::class, 'index']); // This will fail // Right: use controller class only Route::get('/greet', GreetingController::class);
Quick Reference
- Define
__invoke(Request $request)method in your controller. - Use the controller class name directly in your route.
- Single action controllers are great for simple, focused tasks.
Key Takeaways
Single action controllers use the __invoke method to handle requests.
Route directly to the controller class without specifying a method.
They simplify controllers that only need one action.
Always import the controller class correctly in routes.
Avoid specifying methods in routes when using single action controllers.