π What Are Routes in Laravel?
Routes are the entry points for your web application.
Every HTTP request is mapped to a route, which tells Laravel which code to execute.
Types of Routes:
- Web routes β for browser requests
File:routes/web.php - API routes β for APIs
File:routes/api.php
π Basic Route Example
Open routes/web.php and add:
Route::get('/', function () {
return "Welcome to Laravel Routing!";
});
getβ HTTP GET request/β URL pathfunction()β callback executed when route is visited
Visit http://127.0.0.1:8000/ β youβll see the message π
πͺ Route Parameters
Dynamic routes can accept parameters:
Route::get('/user/{id}', function ($id) {
return "User ID: ".$id;
});
{id}β route parameter$idβ received in the closure
Example URL: http://127.0.0.1:8000/user/5 β Output: User ID: 5
π· Named Routes
Named routes help you generate URLs dynamically:
Route::get('/profile', function () {
return "This is your profile";
})->name('profile');
Generate URL in Blade:
<a href="{{ route('profile') }}">Profile</a>
π§ Route Groups & Middleware
Group routes for better organization:
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', function () {
return "Dashboard Page";
});
Route::get('/settings', function () {
return "Settings Page";
});
});
- Only authenticated users can access these routes
authmiddleware β provided by Laravel
π§© Controllers in Laravel
Controllers handle business logic instead of putting everything in routes.
File location: app/Http/Controllers
Create a Controller
php artisan make:controller UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function show($id)
{
return "User Profile ID: ".$id;
}
}
Route to controller:
Route::get('/user/{id}', [UserController::class, 'show']);
Visit: http://127.0.0.1:8000/user/10 β Output: User Profile ID: 10
β‘ Resource Controllers
Laravel makes CRUD easy with resource controllers:
php artisan make:controller PostController --resource
This automatically provides:
| Method | Purpose |
| ------- | ------------------------ |
| index | Show all posts |
| create | Show form to create post |
| store | Save new post |
| show | Show single post |
| edit | Show form to edit post |
| update | Update post |
| destroy | Delete post |
Add resource route:
Route::resource('posts', PostController::class);
Now Laravel handles all 7 RESTful routes automatically.
π Bonus Tips
- Always keep routes clean and meaningful
- Use Route Model Binding for simplicity
- Separate API and Web routes for clarity
- Use middleware for authentication & authorization
π Key Takeaways
This week you learned:
- What routes are and types of routes
- How to use dynamic route parameters
- Named routes & generating URLs
- Using middleware
- How to create controllers and resource controllers