Laravel 8 Routing Explained 🚀
Routing in Laravel 8 allows you to define how your application responds to HTTP requests. It maps URLs to controller methods or closures. Routes are defined in the routes/
directory, mainly in:
routes/web.php
(for web routes using a browser)routes/api.php
(for API routes)
1. Defining Basic Routes
a) Basic GET Route
The simplest way to define a route is using Route::get()
, which listens for GET requests.
use Illuminate\Support\Facades\Route;
Route::get('/welcome', function () {
return 'Welcome to Laravel 8!';
});
✅ When users visit /welcome
, they will see Welcome to Laravel 8!
.
b) Route with Parameters
Required Parameter
You can pass parameters in routes like this:
Route::get('/user/{id}', function ($id) {
return "User ID: " . $id;
});
✅ Visiting /user/5
will output User ID: 5
.
Optional Parameter
Make parameters optional by adding ?
and setting a default value:
Route::get('/post/{slug?}', function ($slug = 'default-post') {
return "Post: " . $slug;
});
✅ Visiting /post
will output Post: default-post
.
2. Routes with Controllers
Instead of defining logic in routes, Laravel allows routing through controllers.
a) Basic Controller Routing
Define a route that calls a controller method:
use App\Http\Controllers\UserController;
Route::get('/profile', [UserController::class, 'show']);
✅ This calls show()
in UserController.php
.
Controller Example (app/Http/Controllers/UserController.php
):
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function show()
{
return "User Profile Page";
}
}
b) Resource Controller (CRUD)
Laravel provides a resource controller for handling CRUD (Create, Read, Update, Delete) operations.
use App\Http\Controllers\ProductController;
Route::resource('products', ProductController::class);
This automatically creates routes for: | Method | URI | Action | |---------|---------------|--------------| | GET | /products | index() | | GET | /products/create | create() | | POST | /products | store() | | GET | /products/{id} | show() | | GET | /products/{id}/edit | edit() | | PUT/PATCH | /products/{id} | update() | | DELETE | /products/{id} | destroy() |
Run this command to create a resource controller:
php artisan make:controller ProductController --resource
3. Named Routes
Laravel allows naming routes for easy reference:
Route::get('/dashboard', function () {
return "Dashboard";
})->name('dashboard');
✅ Generate a URL using:
$url = route('dashboard'); // Returns "/dashboard"
✅ Redirect using:
return redirect()->route('dashboard');
4. Grouping Routes
a) Route Groups
To apply common middleware, prefix, or namespaces, use route groups.
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', function () {
return "User Dashboard";
});
Route::get('/settings', function () {
return "User Settings";
});
});
✅ Both /dashboard
and /settings
require authentication.
b) Route Prefixing
To apply a common prefix to routes:
Route::prefix('admin')->group(function () {
Route::get('/users', function () {
return "Admin Users";
});
Route::get('/reports', function () {
return "Admin Reports";
});
});
✅ URLs will be /admin/users
and /admin/reports
.
5. API Routes (routes/api.php)
Laravel automatically groups API routes under /api/
.
Define API routes in routes/api.php
:
use App\Http\Controllers\Api\UserController;
Route::get('/users', [UserController::class, 'index']);
✅ The full URL will be:
http://yourdomain.com/api/users
6. Route Model Binding
Instead of manually fetching models, Laravel allows route model binding.
use App\Models\User;
use App\Http\Controllers\UserController;
Route::get('/user/{user}', [UserController::class, 'show']);
✅ In UserController.php
:
public function show(User $user)
{
return $user; // Laravel automatically fetches user by ID
}
7. Redirect Routes
Redirect routes to another URL:
Route::redirect('/old-route', '/new-route', 301);
✅ Visiting /old-route
redirects to /new-route
.
8. Fallback Routes
Handle undefined routes using a fallback:
Route::fallback(function () {
return "Page Not Found!";
});
✅ If no routes match, it shows "Page Not Found!"
.
9. Middleware in Routes
Apply middleware to a route:
Route::get('/dashboard', function () {
return "Dashboard";
})->middleware('auth');
✅ Only authenticated users can access /dashboard
.
Conclusion
Laravel 8 routing is powerful and flexible, allowing you to define routes for web and API endpoints, use controllers, apply middleware, and more! 🚀💡
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.