Working with Controllers
# CHAPTER 5
Working with Controllers
1. Introduction
In the previous chapter, we wrote PHP logic directly inside theroutes/web.php file. While this works for a one-page site, building a massive application this way results in a 5,000-line routing file that is impossible to read. In the MVC architecture, the Router should only route traffic; it should hand the actual processing logic off to a Controller. In this chapter, we will learn how to generate Controllers, write methods, and pass data elegantly to our Views.
2. Learning Objectives
By the end of this chapter, you will be able to:- Generate a Controller using the Artisan command-line tool.
- Route web traffic directly to Controller methods.
- Pass variables and arrays from a Controller into a View.
- Understand and utilize Resource Controllers for CRUD operations.
3. Beginner-Friendly Explanation
Imagine a massive hospital. The Receptionist (the Router) sits at the front desk. A patient walks in with a broken arm. The Receptionist does *not* set the bone, apply a cast, and write a prescription right there in the lobby. That would be chaotic! Instead, the Receptionist simply directs the patient to Room 3. In Room 3 is the Doctor (the Controller). The Doctor examines the arm, asks the lab for X-Rays (the Model), writes a diagnosis, and prints a discharge paper (the View). Controllers group related logic together. All logic regarding users goes in theUserController. All logic regarding blog posts goes in the PostController.
4. Creating a Controller via Artisan
Laravel's greatest superpower is its built-in robot assistant, Artisan. Instead of creating files manually and typing out messy PHP class structures, you ask Artisan to do it.Open your terminal and type:
*Magic!* Laravel instantly creates a beautifully formatted file at app/Http/Controllers/UserController.php.
5. Writing a Controller Method
Let's open the newly createdUserController.php and write a method (a function inside a class) to show a profile.
6. Connecting the Route to the Controller
Now, we must tell the Router to stop doing the work itself, and instead forward traffic to theUserController.
In routes/web.php:
7. Reading Data in the View
The Controller usedcompact('user_name', 'id') to pass data to the View. How does the View display it? Laravel uses Blade templating (which we cover deeply in the next chapter). We use double curly braces {{ }} to echo variables.
In resources/views/profile.blade.php:
8. The Ultimate Shortcut: Resource Controllers
If you are building an app with standard CRUD (Create, Read, Update, Delete) operations, a Controller will always need the same 7 methods (index, create, store, show, edit, update, destroy).
Artisan can generate all 7 methods for you instantly!
Terminal Command:
And in your web.php router, you can route all 7 URLs with ONE line of code:
*(This single line automatically handles GET /posts, POST /posts, GET /posts/{id}, DELETE /posts/{id}, etc!)*
9. Best Practices
-
Single Responsibility: If your
UserControlleris handling user logins, user profiles, uploading user avatars, and sending user emails, it is too fat. Break it down. Create anAvatarControlleror anEmailController. Small controllers are easy to maintain.
10. Common Mistakes
-
Forgetting the
useStatement inweb.php: If you writeRoute::get('/', [UserController::class, 'index']);but forget to putuse App\Http\Controllers\UserController;at the very top of the routing file, Laravel will crash with a "Class not found" error.
11. Exercises
- 1. Explain the "Hospital Analogy" to describe why we use Controllers instead of writing logic directly in the routing file.
12. Coding Challenges
-
Challenge: Use the terminal to create a
ProductController. Write anindex()method inside it that returns a view calledproducts.index, and passes an array of three fake product names to that view.
13. MCQs with Answers
What terminal command is used to automatically generate a new Controller file in Laravel?
When a Controller wants to hand variables (data) over to a View so the View can display them, which helper function is most commonly used?
14. Interview Questions
- Q: How do you pass an array of database records from a Controller to a Blade View, and how does the concept of Separation of Concerns apply here?
-
Q: What is a Resource Controller in Laravel, and what specific problem does the
--resourceflag solve for developers building CRUD applications?
15. FAQs
Q: Can a Controller connect to multiple Models? A: Yes! For example, anOrderController might need to ask the Order Model for the receipt data, and ask the User Model for the customer's shipping address, combining them before sending them to the View.
16. Summary
In Chapter 5, we brought order to the chaos. By offloading logic from our routing files into dedicated Controllers, we adhere strictly to the MVC architecture. We learned how to use the Artisan CLI to generate boilerplate code, how to wire our routes to specific Controller methods, and how to seamlessly pass data variables to our Views usingcompact().