In web development, keeping your code organized is the secret to building great applications without getting overwhelmed. If you think of a Route as a restaurant waiter taking an order from a customer, the Controller is the kitchen chef who takes that order, prepares the meal, and sends it back to the table.
Why Do We Need Controllers?
In our earlier guide on routing, we wrote code directly inside routes/web.php. While that works for tiny tests, real-world apps have hundreds of pages. Putting all your logic into your routes file makes it messy and hard to read. A Controller gives your logic a clean, dedicated home.
Creating Your First Controller
Laravel includes a helpful command-line tool called Artisan. To create a new controller, open your terminal inside your project folder and run:
# Ask Artisan to generate a new controller
php artisan make:controller OrderControllerLaravel immediately creates a fresh file located at app/Http/Controllers/OrderController.php.
Writing a Simple Controller Action
Open your new controller in your text editor. Let's create an action called show that returns a greeting:
<?php
namespace App\Http\Controllers;
class OrderController extends Controller
{
// The show method handles incoming customer requests
public function show()
{
$orderName = 'Fresh Coffee';
// Pass the variable to a Blade view
return view('order', ['item' => $orderName]);
}
}Connecting the Controller to a Route
Now, open routes/web.php and connect your waiter (the route) to your chef (the controller):
use App\Http\Controllers\OrderController;
// When visitors go to /order, OrderController runs the show method
Route::get('/order', [OrderController::class, 'show']);3 Things to Remember
- The Analogy: Routes are waiters; Controllers are the kitchen chefs doing the actual work.
- Creation: Run
php artisan make:controller NameControllerto generate one in seconds. - Clean Code: Controllers keep your
routes/web.phpfile neat, short, and easy to manage.