Giao diện
Routing (Định tuyến)
Routing cơ bản (Basic Routing)
Các routes cơ bản nhất trong Laravel chấp nhận URI và closure, cung cấp phương thức đơn giản và biểu cảm:
php
use Illuminate\Support\Facades\Route;
Route::get('/greeting', function () {
return 'Hello World';
});Files Route mặc định (The Default Route Files)
Tất cả routes được định nghĩa trong thư mục routes, tự động tải bởi cấu hình trong bootstrap/app.php. File routes/web.php định nghĩa routes cho giao diện web, được gán nhóm middleware web (cung cấp session state và CSRF protection).
php
use App\Http\Controllers\UserController;
Route::get('/user', [UserController::class, 'index']);API Routes
Bạn có thể kích hoạt API routing bằng lệnh Artisan install:api:
bash
php artisan install:apiLệnh này cài đặt Laravel Sanctum và tạo file routes/api.php. Routes trong routes/api.php là stateless, thuộc nhóm middleware api, với prefix /api tự động:
php
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:sanctum');Thay đổi prefix trong bootstrap/app.php:
php
->withRouting(
api: __DIR__.'/../routes/api.php',
apiPrefix: 'api/admin',
// ...
)Các Router Methods có sẵn
Router cho phép đăng ký routes phản hồi mọi HTTP verb:
php
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);Đôi khi bạn cần đăng ký route phản hồi nhiều HTTP verbs cùng lúc:
php
Route::match(['get', 'post'], '/', function () {
// ...
});
Route::any('/', function () {
// ...
});Redirect Routes
Định nghĩa route chuyển hướng đến URI khác:
php
Route::redirect('/here', '/there');
// Với status code tùy chỉnh
Route::redirect('/here', '/there', 301);
// Hoặc permanent redirect (301)
Route::permanentRedirect('/here', '/there');View Routes
Nếu route chỉ cần trả về view:
php
Route::view('/welcome', 'welcome');
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);Route Parameters
Parameters bắt buộc (Required Parameters)
Bắt các segments từ URI:
php
Route::get('/user/{id}', function (string $id) {
return 'User '.$id;
});
Route::get('/posts/{post}/comments/{comment}', function (string $postId, string $commentId) {
// ...
});Route parameters nằm trong dấu {}, chỉ chứa ký tự chữ cái và underscore (_).
Parameters và Dependency Injection
Liệt kê route parameters sau dependencies:
php
use Illuminate\Http\Request;
Route::get('/user/{id}', function (Request $request, string $id) {
return 'User '.$id;
});Parameters tùy chọn (Optional Parameters)
Đặt dấu ? sau tên parameter và cung cấp giá trị mặc định:
php
Route::get('/user/{name?}', function (?string $name = null) {
return $name;
});
Route::get('/user/{name?}', function (?string $name = 'John') {
return $name;
});Ràng buộc Regular Expression
Ràng buộc format parameter bằng method where:
php
Route::get('/user/{name}', function (string $name) {
// ...
})->where('name', '[A-Za-z]+');
Route::get('/user/{id}', function (string $id) {
// ...
})->where('id', '[0-9]+');
Route::get('/user/{id}/{name}', function (string $id, string $name) {
// ...
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);Laravel cũng cung cấp helper methods:
php
Route::get('/user/{id}/{name}', function (string $id, string $name) {
// ...
})->whereNumber('id')->whereAlpha('name');Named Routes (Routes có tên)
Gán tên cho route để tạo URLs hoặc redirects thuận tiện:
php
Route::get('/user/profile', function () {
// ...
})->name('profile');
Route::get('/user/profile', [UserProfileController::class, 'show'])->name('profile');Tạo URLs cho Named Routes
php
// Tạo URLs...
$url = route('profile');
// Tạo Redirects...
return redirect()->route('profile');
return to_route('profile');Với parameters:
php
Route::get('/user/{id}/profile', function (string $id) {
// ...
})->name('profile');
$url = route('profile', ['id' => 1]);
// Thêm query string tự động
$url = route('profile', ['id' => 1, 'photos' => 'yes']);
// → http://example.com/user/1/profile?photos=yesRoute Groups (Nhóm Routes)
Route groups cho phép chia sẻ attributes (middleware, prefix, v.v.) giữa nhiều routes.
Middleware
php
Route::middleware(['first', 'second'])->group(function () {
Route::get('/', function () {
// Dùng middleware first & second...
});
Route::get('/user/profile', function () {
// Dùng middleware first & second...
});
});Controllers
php
use App\Http\Controllers\OrderController;
Route::controller(OrderController::class)->group(function () {
Route::get('/orders/{id}', 'show');
Route::post('/orders', 'store');
});Subdomain Routing
php
Route::domain('{account}.example.com')->group(function () {
Route::get('/user/{id}', function (string $account, string $id) {
// ...
});
});Route Prefixes
php
Route::prefix('admin')->group(function () {
Route::get('/users', function () {
// Khớp URL "/admin/users"
});
});Route Name Prefixes
php
Route::name('admin.')->group(function () {
Route::get('/users', function () {
// Route name: "admin.users"...
})->name('users');
});Route Model Binding
Khi inject model ID vào route/controller action, Laravel cung cấp cách tự động inject model instance trực tiếp. Thay vì inject ID, bạn inject toàn bộ User model.
Implicit Binding
Laravel tự động phân giải Eloquent models khi tên biến type-hint khớp với tên route segment:
php
use App\Models\User;
Route::get('/users/{user}', function (User $user) {
return $user->email;
});Explicit Binding
Đăng ký explicit binding trong method boot của AppServiceProvider:
php
use App\Models\User;
use Illuminate\Support\Facades\Route;
public function boot(): void
{
Route::model('user', User::class);
}Fallback Routes
Định nghĩa route xử lý khi không route nào khớp:
php
Route::fallback(function () {
// ...
});Rate Limiting (Giới hạn tốc độ)
Định nghĩa Rate Limiters
Định nghĩa trong method boot của AppServiceProvider bằng RateLimiter facade:
php
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});Gán Rate Limiters cho Routes
php
Route::middleware(['throttle:api'])->group(function () {
Route::get('/audio/{id}', function (string $id) {
// ...
});
});Form Method Spoofing
HTML forms không hỗ trợ PUT, PATCH, DELETE. Thêm field ẩn _method:
html
<form action="/example" method="POST">
@method('PUT')
@csrf
</form>Truy cập Route hiện tại (Accessing the Current Route)
php
use Illuminate\Support\Facades\Route;
$route = Route::current(); // Illuminate\Routing\Route
$name = Route::currentRouteName(); // string
$action = Route::currentRouteAction(); // stringCross-Origin Resource Sharing (CORS)
Laravel tự động xử lý CORS OPTIONS requests qua middleware HandleCors. Tùy chỉnh bằng cách publish cấu hình:
bash
php artisan config:publish corsRoute Caching
Khi deploy, sử dụng route cache để tăng tốc:
bash
php artisan route:cacheXóa cache:
bash
php artisan route:clear