Laravel 11's invokable controllers offer a powerful and focused approach to handling specific actions within your application. This guide delves into the creation and usage of these controllers, highlighting their benefits and providing a practical example.
Benefits of Invokable Controllers:
- Enhanced Readability: With a single
__invoke
method, the controller's purpose becomes crystal clear, promoting code maintainability and understanding. - Reduced Complexity: Less code translates to easier maintenance and a streamlined development process.
- Concise Routing: You can directly reference the controller class in your Laravel 11 routes without specifying a method, simplifying route definitions.
Crafting an Invokable Controller in Laravel 11
Utilize the Artisan Command
- Open your terminal and navigate to your Laravel 11 project's root directory.
- Execute the following command, replacing
YourControllerName
with your desired name:php artisan make:controller YourControllerName --invokable
This command creates a new controller class with the __invoke
method at its core, ready for your custom logic.
Structure the __invoke
Method
- Open the generated controller file (usually located in
app/Http/Controllers
). - You'll find the
__invoke
method already defined. This is where your controller's logic resides. - Access the request object using the
Request
type hint:public function __invoke(Request $request) { // Your controller logic here }
- Implement the desired functionality within this method, leveraging Laravel's features like repositories, models, and validation as needed.
Define Routes
- In your routes file (typically
routes/web.php
), create a route to match the desired URL:Route::get('/your-route', YourControllerName::class);
- Replace
/your-route
with your preferred URI andYourControllerName
with the actual controller class name.
Example: Processing a Simple Form Submission with an Invokable Controller
// app/Http/Controllers/ProcessFormController.php
class ProcessFormController
{
public function __invoke(Request $request)
{
$request->validate([
'name' => 'required|string',
'email' => 'required|email',
]);
// Process the form data (e.g., save to database)
return redirect('/success');
}
}
// routes/web.php
Route::post('/submit-form', ProcessFormController::class);
By following these steps, you can create efficient and maintainable invokable controllers in Laravel 11, promoting cleaner code and a streamlined development experience.