Imagine walking into a large office building. At the front desk, a friendly directory sign tells you: "Looking for Billing? Go to Room 201. Looking for Support? Go to Room 105." Without that directory, visitors would wander around lost.
In Laravel, Routes are that front-desk directory, and Controllers are the helpful staff members inside each room who prepare what the visitor needs.
What Is a Route in Laravel?
Every time someone types a web address like yoursite.com/hello, Laravel looks inside a file called routes/web.php. A route simply connects a URL path to an action.
<?php
use Illuminate\Support\Facades\Route;
// When a visitor opens /hello, show a friendly message
Route::get('/hello', function () {
return 'Hello, welcome to my first Laravel page!';
});
Putting small responses directly in routes/web.php works great for testing. However, as your website grows, putting all your logic inside one file becomes messy—just like having every staff member sit at the front desk!
Moving Logic into a Controller
A Controller is a dedicated PHP class that keeps your page logic neat and organized. You can create one in seconds using Artisan, Laravel's built-in helper command:
# Create a new controller named WelcomeController
php artisan make:controller WelcomeController
Laravel creates the file at app/Http/Controllers/WelcomeController.php. Now we can add a simple function (called a method) inside it:
<?php
namespace App\Http\Controllers;
class WelcomeController extends Controller
{
// This method handles the /hello page
public function sayHello()
{
return 'Hello from the WelcomeController!';
}
}
Connecting the Route to the Controller
Finally, update routes/web.php so the front desk points visitors straight to your new controller:
<?php
use App\Http\Controllers\WelcomeController;
use Illuminate\Support\Facades\Route;
// Point /hello to the sayHello method inside WelcomeController
Route::get('/hello', [WelcomeController::class, 'sayHello']);
Now when someone visits /hello, Laravel reads the route, calls WelcomeController, and displays the greeting cleanly.
3 Things to Remember
- Routes live in
routes/web.phpand act like a map connecting URLs to actions. - Controllers live in
app/Http/Controllers/and keep your page logic tidy instead of crowding your routes file. - Use
php artisan make:controller NameControllerto generate a new controller file automatically.