# Route 路由 路由負責管理網站所有的請求行為,根據訪問的網址以及請求動詞(GET.POST)來決定交由哪一個控制器的方法來處理 負責的檔案 一般使用者透過瀏覽器所進行的請求都會交由routes/web.php來設定 而API相關的請求則是交由routes/api.php來設定 編寫路由規則 Route::get('路徑','App\Http\Controllers\HomeController@index'); get 請求動詞 路徑 網址路徑 控制器 負責處理此請求的控制器,8.x之後需要加上命名空間 方法 負責處理此請求的方法 規則判定由上至下逐一比對,只要符合路徑就傳遞給控制器 8.X之後支援的新寫法 use App\Http\Controllers\HomeController; Route::get(‘路徑’,[HomeController::class,‘index’]); 直接在路由檔裡面耍流氓 你可以不經由控制器裡的方法來處理請求,直接在路由檔內搞定,但不建議這樣做 Route::get('路徑',function(){ return 'Hello!'; }); Route Model Binding 只要在參數前宣告模型類別,並且路徑參數取為同名,就會自動為你用id進資料庫查詢該表,直接提供model物件給你 必要條件: 路徑參數需與函式參數名稱相同 函式參數前面需宣告類別,且名稱相同 Route::get('api/users/{user}', function (App\User $user) { return $user->email; }); 關於控制器 位於app/Http/Controllers資料夾,可建立子資料夾 建立檔案的指令 php artisan make:controller HomeController 路由可傳遞參數 Route::get('路徑/{id}',function($id){ return 'Hello ' . $id; }); 可傳遞多個參數 Route::get('路徑/{id}/{name}',function($id,$name){ return 'Hello ' . $id . ',Name is ' . $name; }); 可傳可不傳遞參數 Route::get('路徑/{id?}',function($id = 1){ return 'Hello ' . $id; }); 設定路由群組 Route::group(['prefix' => 'demo'],function(){ Route::get('hello', function () { return 'Hello' ; }); Route::get('world', function () { return 'World'; }); }); 設定路由名稱 //routes/web.php Route::get('demo/{id}','App\Http\Controllers\HomeController@index')->name('home.index'); //resources/views/show.blade.php <a href="{{ route(‘home.index’, [‘id’=>1]) }}">總覽頁</a> 進行轉址 外部轉址 //routes/web.php Route::get(‘baha’,function(){ return redirect(‘https://goblinlab.org’); }); 內部轉址 //routes/web.php Route::get(‘redirect’,function(){ return redirect(url(‘hello’)); }); 相關名詞說明 SPA Single Page Application 將網頁做成類似一般App應用樣貌的一頁式操作 Closure 沒有名稱的匿名函式,一般用於封包程式碼且只用一次 Facade Laravel所提供的工具類別,包含大量好用的類別函式 Middleware 中介層,符合條件的請求在處理前會先執行的內容 發表於 HackMD 151 讚賞 收藏 訂閱