iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 10
0
Software Development

30天快速上手Laravel系列 第 10

Day10-[Laravel 資料夾目錄與內容] Route (HTTP 路由) part 1

介紹

在laravel 中定義route的位置

5.2版本之前 app/Http/routes.php
5.3版本之後 有提供routes資料夾在目錄中

還有一個也會影響route設定的地方
app/Providers/AppServiceProvider.php

基本寫法

Route::get('/user', 'UserController@index');

Route提供的Https verb 方法

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

如果一個route 要可以有多種回應可以用 match 甚至是 any

進階寫法

另外關於route 還有提供很多種方法和實作細節,底下舉幾個用法

Redirect: 重新導向的route

Route::redirect('/here', '/there', 301);

Views: 只回傳view的route

Route::view('/welcome', 'welcome', ['name' => 'Taylor']);
第三個參數 ['name' => 'Taylor'] 這個是要另外傳給前端的data,非必填。

Route Parameters

直接帶參數:

Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
    //
});
Route::get('posts/{post}/comments/{comment}', 'CommentController@getSpecificComment');

選擇性參數 [參數帶入問號 => 可不傳name參數]

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

注意,route變數命名({})裡面不能含 -,如果要分隔字的話需使用 _分隔。

Named Routes


另外也可以命名參數,讓他在其他地方也可以方便被取用
Route::get('user/profile', 'UserProfileController@show')->name('profile');

  • 更多route的用法可以參考: laravel routing
  • 關於Resource Route [中文可能會說是資源控制器],之後會在Controller章節提到

上一篇
Day9-[Laravel 資料夾目錄與內容] 應用程式(資料夾)目錄
下一篇
Day11-[Laravel 資料夾目錄與內容] Route (HTTP 路由) part 2
系列文
30天快速上手Laravel30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言