1. Route Parameters

Để thêm parameter lên URI các bạn đơn giản khai báo tên parameter trong dấu braces ({})

Route::get('/user/{id}', function (string $id) {
    return 'User '.$id;
});
Route::get('/posts/{post}/comments/{comment}', function (string $postId, string $commentId) {
    // ...
});

Nếu parameters là optional (tùy chọn), thì các bạn khai báo thêm dấu ? vào sau tên parameters

Route::get('/user/{name?}', function (?string $name = null) {
    return $name;
});
 
Route::get('/user/{name?}', function (?string $name = 'John') {
    return $name;
});

Để thêm ràng buộc cho parameters (kiểu như giá trị của parameters phải là dạng số, alphabet, …), các bạn add thêm method “where” để define. Cái này gọi là Regular Expression Constraints

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]+']);

Trong Laravel có sẵn các helper method, giúp nhanh chóng define các Regular Expression, ví dụ

Route::get('/user/{id}/{name}', function (string $id, string $name) {
    // ...
})->whereNumber('id')->whereAlpha('name');
 
Route::get('/user/{name}', function (string $name) {
    // ...
})->whereAlphaNumeric('name');
 
Route::get('/user/{id}', function (string $id) {
    // ...
})->whereUuid('id');
 
Route::get('/user/{id}', function (string $id) {
    //
})->whereUlid('id');
 
Route::get('/category/{category}', function (string $category) {
    // ...
})->whereIn('category', ['movie', 'song', 'painting']);

Nếu như value không thỏa mãn các constraints thì một lỗi 404 sẽ được trả về

Các bạn cũng có thể define global constraints bằng các add logic vào hàm boot của Provider. Có nghĩa là tất cả các routes đều áp dụng constraints này

/**
 * Define your route model bindings, pattern filters, etc.
 */
public function boot(): void
{
    Route::pattern('id', '[0-9]+');
}

Trong trường hợp value của parameters có chưa dấu gạch chéo ‘/’, giả sử bạn có một route

Route::get('/search/{search}', function (string $search) {
    return $search;
});

Khi bạn gọi: https://your_domain/search/timkiem/iphone/samsung, bạn đang cố gắng truyền param “timkiem/iphone/samsung”, nhưng do value này chứa dấu ‘/’ nên hệ thống không thể xác định được route này.

Để khắc phục điều này thì hãy làm như sau

Route::get('/search/{search}', function (string $search) {
    return $search;
})->where('search', '.*');

2. Named Routes

Để đặt tên cho routes một cách dễ nhớ ngắn gọn, hãy làm như sau

Route::get('/user/profile', function () {
    // ...
})->name('profile');

Lưu ý rằng tên routes nên đặt là duy nhất.

Với việc đặt tên routes, bạn có thể gọi ra route bằng cách

$url = route('profile');

Hoặc redirect tới route

return redirect()->route('profile');
 
return to_route('profile');

Hoặc truyền value parameters

Route::get('/user/{id}/profile', function (string $id) {
    // ...
})->name('profile');
 
$url = route('profile', ['id' => 1, 'photos' => 'yes']);
 
// /user/1/profile?photos=yes

Check một request có route named. Ví dụ muốn kiểm tra xem request hiện tại có phải là route “profile” hay không, hãy sử dụng $request->route()->named(‘profile’)

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
 
/**
 * Handle an incoming request.
 *
 * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
 */
public function handle(Request $request, Closure $next): Response
{
    if ($request->route()->named('profile')) {
        // ...
    }
 
    return $next($request);
}

Tạm thời dừng lại đây thôi, phần tiếp theo chúng ta sẽ tìm hiểu Routes Group 😉 Happy coding.

By HNK

Leave a Reply

Your email address will not be published. Required fields are marked *