基礎路由
最基礎的Laravel路由(Routing)由一個URI和閉包(Closure)組成,是一個簡單且容易理解的定義路由方法:Route::get('foo', function () {
return 'Hello World';
});
預設的路由檔案
所有Laravel路由都在路由檔案內定義,並存放在在目錄 routes,框架會自動被載入這些檔案,檔案routes/web.php定義web層的路由,這些路由被歸類到web中介軟體(middleware)提供session state和CSRF protection;而在routes/api.php是stateless,屬於api這個middleware。在大部分的應用裡,你會從檔案routes/web.php開始定義路由,檔案routes/web.php內的路由將可以透過定義的URL在瀏覽器開啟,例如:你可以在瀏覽器存取下列的路由http://your-app.test/user:
Route::get('/user', 'UserController@index');檔案routes/api.php內的路由在RouteServiceProvider被設定成一個路由群組(Route group),在這個組裡,所有的路由將自動補上前綴(prefix)/api,不需要手動在每個路由設定,可以在RouteServiceProvider修改前綴,或定義其他路由組。※路徑:./app/Providers/RouteServiceProvider.php
提供的路由方法(Available Router Methods)
提供你註冊路由來回應任何HTTP的動作(verbs):Route::get($uri, $callback); Route::post($uri, $callback); Route::put($uri, $callback); Route::patch($uri, $callback); Route::delete($uri, $callback); Route::options($uri, $callback);有時你可能需要註冊一個可以回應多種HTTP動作的路由,你可以使用match,或你也可以透過any來註冊一個回應所有HTTP動作的路由。
Route::match(['get', 'post'], '/', function () {
//
});
Route::any('/', function () {
//
});CSRF保護機制
任何HTML的表單只要是指向POST、PUT和DELETE的路由,都需要一個CSRP的欄位,否則,請求將被回拒,你可以在CSRF documentation了解更多關於CSRF protection。<form method="POST" action="/profile">
@csrf
...
</form>重新導向路由(Redirect Routes)
如果要定義一個路由會重新導向到其他URI,你可以使用Route::redirect,這個方法提供一個方便的捷徑,讓你不需要定義完整的路由或控制器(controller)來實現簡單的重新導向:Route::redirect('/here', '/there');預設情況,Route::redirect會回傳302的HTTP狀態碼(HTTP status code),你可以用第三個可選參數來自訂狀態碼:Route::redirect('/here', '/there', 301);你也可以用Route::permanentRedirect來回傳301的狀態碼:Route::permanentRedirect('/here', '/there');視圖路由(View Routes)
如果你的路由僅需回傳一個視圖(view),你可以使用Route::view,就像是redirect,這個方法提供一個簡單的捷徑免於定義完整的路由和控制器,view這個方法可以傳入URI當作第一個參數,用第二個參數為此路由命名。此外,第三個非必選的參數可以傳入一個陣列的資料給視圖使用。Route::view('/welcome', 'welcome');
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);路由參數
必填的參數(Required Parameters)
有時你需要擷取URI的一部份,例如:你需要從URL獲得使用者的ID,你可以這樣定義路由參數:Route::get('user/{id}', function ($id) {
return 'User '.$id;
});你可以在路由中視需求定義多個路由參數:Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
//
});路由參數必須被{}包起來,名稱為字母組成並不能有-,可以使用底線(_)來取代-,路由參數將會按照順序傳入路由的回調(callbacks)/控制器(controllers),因此取名不重要可以自行定義。選填的參數(Optional Parameters)
偶爾你需要一個特定的路由參數,但希望這個參數不是一個必填的欄位,你可以放置?的標記在參數名稱後,最後請確定你為路由參數設定了一個相應的預設值。Route::get('user/{name?}', function ($name = null) {
return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
return $name;
});關係表示式限制
你可以使用where對路由參數的模式賦予限制,方法where傳入參數的名稱和一個定義限制為何的關係表示式(Regular Expression):Route::get('user/{name}', function ($name) {
//
})->where('name', '[A-Za-z]+');
Route::get('user/{id}', function ($id) {
//
})->where('id', '[0-9]+');
Route::get('user/{id}/{name}', function ($id, $name) {
//
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);全域限制(Global Constraints)
如果你希望路由參數可以一直遵守給定的限制,你可以使用pattern,你可以在檔案RouteServiceProvider的boot方法裡定義這些模式:/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
Route::pattern('id', '[0-9]+');
parent::boot();
}一旦這些模式被定義,將會自動應用到所有使用這個參數名稱的路由:Route::get('user/{id}', function ($id) {
// Only executed if {id} is numeric...
});編碼正斜杠(Encoded Forward Slashes)
Laravel路由允許任何字元,除了/,你必須使用where設定關係表達式(regular expression),明確地開放/納入佔位符(placeholder)的一部份。Route::get('search/{search}', function ($search) {
return $search;
})->where('search', '.*');[!] 編碼正斜杠只對路由的最後一個部份有效命名路由
命名路由(Named routes)讓產生URLs或重新導向到特定的路由變得方便,你可以透過name連結到路由的定義來指定一個名稱給路由。Route::get('user/profile', function () {
//
})->name('profile');
你也可以為控制器動作(controller actions)指定路由名稱:Route::get('user/profile', 'UserProfileController@show')->name('profile');
產生命名路由的URLs(Generation URLs To Named Routes)
一旦你為路由設定名稱,你可以用這個路由名稱產生URL或使用函式route重新導向:// Generating URLs...
$url = route('profile');
// Generating Redirects...
return redirect()->route('profile');
若這個命名路由有參數(parameters),你可以在函式route作為第二個傳遞參數,參數將會自動在正確的位置插入URL。Route::get('user/{id}/profile', function ($id) {
//
})->name('profile');
$url = route('profile', ['id' => 1]);
檢查目前的路由(Inspecting The Current Route)
如果你需要確認目前的請求要引導的命名路由,你可以在Route的實例中使用named方法,例如:你可以在路由中介軟體確認路由名稱。/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->route()->named('profile')) {
//
}
return $next($request);
}路由群組(Route Groups)
路由組可以允許大量的路由共用路由的屬性,像是中介軟體〈middleware〉或命名空間〈namespaces〉,而非在路由中個別獨立設定。共用的屬性以陣列格式作為Route :: group方法的第一個參數。中繼軟體(Middleware)
你可以在路由群組的定義之前,用middleware將群組的所有路由設定中繼軟體,中間軟體將按照它們列出的順序執行:Route::middleware(['first', 'second'])->group(function () {
Route::get('/', function () {
// Uses first & second Middleware
});
Route::get('user/profile', function () {
// Uses first & second Middleware
});
});
取得現在的路由
你可以使用current、currentRouteName及currentRouteAction這些Route方法,取得關於路由的資訊來處理進來的請求。$route = Route::current(); $name = Route::currentRouteName(); $action = Route::currentRouteAction();
文章來源:https://laravel.com/docs/5.8/routing
沒有留言:
張貼留言