在 laravel 裡我們設定一個 route 時,為了方便,可以替他設定一個名字,像是這樣:

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

 

如果有要使用 controller 的話則是寫成這樣:

Route::get(
    '/user/profile',
    [UserProfileController::class, 'show']
)->name('profile');

 

當設定好 name 了以後,我們要連結頁面,就可以使用 route 來取代原本的網址

// Generating URLs...
$url = route('profile');

// Generating Redirects...
return redirect()->route('profile');

 

網址如果有參數的話:

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

$url = route('profile', ['id' => 1]);

 

額外的參數,一般是給 get 用的:

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

$url = route('profile', ['id' => 1, 'photos' => 'yes']);

// /user/1/profile?photos=yes

 

要取得當下的 route name 的方法:

\Request::route()->getName()

 

判斷是否是該個 route name

if ($request->route()->named('profile')) {
        //
    }