Controllers in Laravel
β± Estimated reading time: 2 min
Controllers in Laravel are responsible for handling incoming HTTP requests and returning responses. They act as an intermediary between routes and views/models, helping keep application logic organized and maintainable. Controllers are a core part of Laravelβs MVC (ModelβViewβController) architecture.
1. What Is a Controller?
A controller groups related request-handling logic into a single class. Instead of writing all logic inside route files, controllers help structure code in a clean and reusable way.
Example flow:
2. Creating a Controller
Laravel provides Artisan commands to create controllers.
This creates a controller file in:
3. Basic Controller Structure
Example of a simple controller:
4. Connecting Controllers to Routes
To use a controller method, define it in a route:
When /users is accessed, the index method is executed.
5. Controllers with Views
Controllers commonly return views:
The view file should be located at:
6. Passing Data to Views
Controllers can send data to views:
In the view:
7. Request Handling in Controllers
Laravel automatically injects the Request object:
8. Resource Controllers
Resource controllers handle CRUD operations:
This generates methods like:
-
index
-
create
-
store
-
show
-
edit
-
update
-
destroy
Used with:
9. Middleware in Controllers
Middleware can be applied inside controllers:
This restricts access to authenticated users.
10. Single-Action Controllers
Controllers with one method use the __invoke method:
Example:
Conclusion
Controllers in Laravel help manage application logic efficiently by separating responsibilities. They improve code readability, reusability, and scalability, making Laravel applications easier to maintain and extend.
Register Now
Share this Post
β Back to Tutorials