Laravel 12 Controllers: A Comprehensive Guide
Laravel 12 continues to uphold the MVC (Model-View-Controller) architecture, with controllers playing a pivotal role in handling HTTP requests and orchestrating application logic. This guide delves into the enhancements and practices for controllers in Laravel 12.
📂 Understanding Controllers in Laravel 12
Controllers in Laravel serve as intermediaries between models and views, managing the flow of data and user interactions. They encapsulate related request handling logic, promoting organized and maintainable codebases.
🛠️ Creating Controllers
To generate a basic controller:
php artisan make:controller CategoryController
This command creates app/Http/Controllers/CategoryController.php, ready for method definitions.
Resource Controller
For CRUD operations, Laravel offers resource controllers:
php artisan make:controller CategoryController --resource
This scaffolds methods like index(), create(), store(), show(), edit(), update(), and destroy().
Route Definitions
Resource controllers can be linked to routes succinctly:
Route::resource('categories', CategoryController::class);
Route::resource('categories', CategoryController::class);
🔄 Single-Action Controllers
For controllers handling a single action, Laravel supports invokable controllers:
php artisan make:controller HomeController --invokable
This creates a controller with an __invoke() method:
class HomeController extends Controller
{
public function __invoke()
{
return view('home');
}
}
Routes can then be defined as:
Route::get('/', HomeController::class);
🧪 Testing Controllers
Laravel’s testing tools facilitate controller testing:
public function testIndex()
{
$response = $this->get('/categories');
$response->assertStatus(200);
$response->assertViewIs('categories.index');
}
This ensures the controller’s index method returns the correct view with a successful response.
📝 Conclusion
Laravel 12’s controller enhancements streamline application development, offering flexibility through basic, resource, and single-action controllers. By adhering to these practices, developers can build robust and maintainable applications.
For more detailed information, refer to the Laravel 12 documentation on controllers.