Skip to main content
Laravel Basics Tutorial
CHAPTER 05 Beginner

Working with Controllers

Updated: May 14, 2026
20 min read

# CHAPTER 5

Working with Controllers

1. Introduction

In the previous chapter, we wrote PHP logic directly inside the routes/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 the UserController. 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:

bash
1
php artisan make:controller UserController

*Magic!* Laravel instantly creates a beautifully formatted file at app/Http/Controllers/UserController.php.

5. Writing a Controller Method

Let's open the newly created UserController.php and write a method (a function inside a class) to show a profile.
php
1234567891011121314151617
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UserController extends Controller
{
    // Create a public method named 'show'
    public function show($id)
    {
        // 1. We will pretend we fetched this name from the database
        $user_name = "Alice";
        
        // 2. We return a view and PASS the data to it!
        // We use the compact() function to easily pass variables
        return view(&#039;profile', compact('user_name', 'id'));
    }
}

6. Connecting the Route to the Controller

Now, we must tell the Router to stop doing the work itself, and instead forward traffic to the UserController.

In routes/web.php:

php
1234567
<?php
use Illuminate\Support\Facades\Route;
// Don't forget to import the Controller at the top!
use App\Http\Controllers\UserController;

// When someone hits /user/5, trigger the 'show' method in UserController
Route::get(&#039;/user/{id}', [UserController::class, 'show']);

7. Reading Data in the View

The Controller used compact('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:

html
123
<h1>User Profile Dashboard</h1>
<p>Viewing Profile ID: {{ $id }}</p>
<p>Welcome back, {{ $user_name }}!</p>

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:

bash
1
php artisan make:controller PostController --resource

And in your web.php router, you can route all 7 URLs with ONE line of code:

php
1
Route::resource(&#039;posts', PostController::class);

*(This single line automatically handles GET /posts, POST /posts, GET /posts/{id}, DELETE /posts/{id}, etc!)*

9. Best Practices

  • Single Responsibility: If your UserController is handling user logins, user profiles, uploading user avatars, and sending user emails, it is too fat. Break it down. Create an AvatarController or an EmailController. Small controllers are easy to maintain.

10. Common Mistakes

  • Forgetting the use Statement in web.php: If you write Route::get('/', [UserController::class, 'index']); but forget to put use App\Http\Controllers\UserController; at the very top of the routing file, Laravel will crash with a "Class not found" error.

11. Exercises

  1. 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 an index() method inside it that returns a view called products.index, and passes an array of three fake product names to that view.

13. MCQs with Answers

Question 1

What terminal command is used to automatically generate a new Controller file in Laravel?

Question 2

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 --resource flag solve for developers building CRUD applications?

15. FAQs

Q: Can a Controller connect to multiple Models? A: Yes! For example, an OrderController 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 using compact().

17. Next Chapter Recommendation

Our Controller is passing data to the View, but our Views currently look very basic. It's time to master Laravel's incredible HTML engine. Proceed to Chapter 6: Blade Templating Engine.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·