邊學邊做laravel(3) HTTP基礎路由
1,415 total views, 2 views today
laravel的路由是事先規劃客戶端的需求,定義每個URL指向的控制器,並做出適當的回應,在5.3之後的版本已經將原本 /app/http/routes.php分成兩個檔案,一個是 /routes/web.php,它被分配到web的中間組件(Middleware),因此可以透過此路由進而使用session與csrf防護等功能, 另一個是/routes/api.php則是無狀態的被分配到api的中間組件(Middleware),網站的基本路由通常設定在 web.php檔案裡面。
在laravel框架裡面一個http request的過程,從1~5依序執行,雖然不推薦但是demo範例中使用的是路油直接透過視圖產生html給瀏覽器。
基礎路由
透過註冊各種路由來回應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);
[/php]
也能使用match來過濾篩選要回應的方法,或是使用any來註冊所有HTTP的請求
[php]
Route::match([‘get’, ‘post’], ‘/’, function () {
// 使用 get 與 post
});
Route::any(‘foo’, function () {
// 任何方法
});
[/php]
CSRF防護
在laravel中如果請求方法是 PUT、POST或是DELETE的HTML表單都必須要有一個CSRF的Token,否則會出現錯誤訊息,要使用CSRF只需要在view的模板中加入 {{ csrf_field() }} 即可自動產生,非常方便。
[html]
<form method=”POST” action=”/profile”>
{{ csrf_field() }}
…
</form>
[/html]
路由參數
必選參數
當我們需要在路由中取得值,例如要取得http://localhost/user/eric中的使用者eric,需加入下列程式碼定義路由參數,編輯 /routes/web.php
[php]
Route::get(‘user/{id}’, function ($id) {
return ‘User ‘.$id;
});
[/php]
開啟google瀏覽器輸入http://localhost/user/eric
也可以同時定義多個路由參數,編輯 /routes/web.php
[php]
Route::get(‘posts/{post}/comments/{comment}’, function ($postId, $commentId) {
return ‘postS= ‘.$postId . ” ——- “. ‘comment= ‘ . $commentId;
});
[/php]
開啟google瀏覽器輸入http://localhost/posts/000/comments/999
可選參數
有時候可能需要指定可選的路由參數(通常僅能在最後一個使用),只要加入 ? 符號即可實現,但是在這樣的設定最好要給予預設值,不然容易發生錯誤。
[php]
Route::get(‘posts/{post}/comments/{comment?}’, function ($postId, $commentId) {
return ‘postS= ‘.$postId . ” ——- “. ‘comment= ‘ . $commentId;
});
[/php]
上面的程式碼沒有加上預設值,當comments後面沒有接東西,就會出現錯誤了
正確的寫法應該是
[php]
Route::get(‘posts/{post}/comments/{comment?}’, function ($postId, $commentId=’123456′) {
return ‘postS= ‘.$postId . ” ——- “. ‘comment= ‘ . $commentId;
});
[/php]
當沒有帶入數值時,自動用預設值套入
正規約束
可以透過 where 使用正規表示式的方法來約束路由器的格式
[php]
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]+’]);
[/php]
命名路由
主要是方便視圖產生URL網址,使用的方法很簡單,只需要在後面使用 -> 加上路由名稱,例如…
[php]
Route::get(‘user/showme’, function () {
//
})->name(‘showme’);
[/php]
在視圖裡面就可以使用輔助參數 route 來產生URL,也能使用 redirect轉址。
編輯 /resources/views/welcome.blade.php,找個適當的地方加入
[html]
<div class=”content”>
<div class=”title m-b-md”>
{{ route(‘showme’) }}
</div>
<div class=”links”>
<a href=”https://laravel.com/docs”>Documentation</a>
<a href=”https://laracasts.com”>Laracasts</a>
<a href=”https://laravel-news.com”>News</a>
<a href=”https://forge.laravel.com”>Forge</a>
<a href=”https://github.com/laravel/laravel”>GitHub</a>
</div>
</div>
[/html]
打開瀏覽器後,直接顯示正確的url網址
如果使用
[html]
{{ route(‘showme’, [‘id’ => 1]) }}
[/html]
則傳回 http://localhost/user/showme?id=1