--- tags: PHP, Backend, Laravel --- # Laravel 路由 ## 基本路由 首先看到rotues資料夾裡的web.php,會看到這些程式碼 ```php= Route::get('/', function () { // 使用get方法請求 return view('welcome'); // 回傳view給他 }); ``` view的位置就放在`resources\views\welcome.blade.php` 接下來說說來說說基本路由 Laravel 的路由只接受一個 URI 和一個Closure(閉包) ```php= Route::get('foo', function () { return 'Hello World'; }); ``` laravel 可以使用所有HTTP的方法 ```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); ``` 可能你這個路由可以響應多個HTTP的請求,可以使用match,或者任何請求都可以就使用any ```php= Route::match(['get', 'post'], '/', function () { // }); Route::any('foo', function () { // }); ``` 如果有將路由指向任何HTML表單POST,PUT或DELETE放在`web.php`中,應當包括CSRF令牌字段。否則,請求將被拒絕。 ```htmlembedded= <form method="POST" action="/profile"> {{ csrf_field() }} ... </form> ``` ## 路由參數 ### 所需參數 有時需要捕捉路由中的URI字段,可以通過以下方式實現 ```php= Route::get('user/{id}', function ($id) { return "User: $id"; }); ``` 如下圖所示: ![](https://i.imgur.com/rIkt6kb.jpg) 可以根據自己的想法來定義更多的路線參數 ```php= Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) { // }); ``` ### 可選參數 有時可能需要指定一個路由參數,但將該路由參數的存在設為可選。您可以通過?在參數名稱後放置一個標記來實現。確保給路由對應的變量一個默認值: ```php= Route::get('user/{name?}', function ($name = null) { return $name; }); Route::get('user/{name?}', function ($name = 'John') { return $name; }); ``` ### 正規表達法約束 您可以使用where路由實例上的方法來限制路由參數的格式。該where方法接受參數的名稱和定義參數應如何約束的正則表達式: ```php= Route::get('user/{name}', function ($name) { // })->where('name', '[A-Za-z]+'); // 他就會找出$name這個參數,符合規則的字段 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]+']); ``` #### 全局約束 如果您希望路由參數始終受給定正則表達式的約束,則可以使用該pattern方法。您應該在`boot`您的方法中定義這些模式`RouteServiceProvider`: ```php= /** * Define your route model bindings, pattern filters, etc. * * @return void */ public function boot() { Route::pattern('id', '[0-9]+'); parent::boot(); } ``` 一旦定義了模式,它就會自動應用於使用該參數名稱的所有路由: ```php= Route::get('user/{id}', function ($id) { // Only executed if {id} is numeric... }); ``` ## 命名路由 命名路由允許為特定路由方便地生成 URL 或重定向。您可以通過將name方法鏈接到路由定義來為路由指定名稱: ```php= Route::get('user/profile', function () { // })->name('profile'); ``` 您還可以為控制器操作指定路由名稱: ```php= Route::get('user/profile', 'UserController@showProfile')->name('profile'); ``` 生成命名路由的 URL 為給定路由指定名稱後,您可以在通過全局route函數生成 URL 或重定向時使用該路由的名稱: ```php= // Generating URLs... $url = route('profile'); // Generating Redirects... return redirect()->route('profile'); ``` 如果命名路由定義了參數,您可以將參數作為第二個參數傳遞給route函數。給定的參數將自動插入到 URL 的正確位置: ```php= Route::get('user/{id}/profile', function ($id) { // })->name('profile'); $url = route('profile', ['id' => 1]); ```