Laravel – Route 功能

<?php
//Route Method有以下幾種
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($uri, $callback);
Route::any($uri, $callback);

//瀏覽器通過 http://127.0.0.1/hello 便會觸發以下
Route::get('hello', function(){
  return 'welcome';
});

//如果需要同時響應多種Route Method 可透過match來實現 或用any響應所有route method
Route::match(['get','post'], 'foo', function(){
  return 'This is a request from get or post';
});

Route::any('bar', function(){
  return 'This is a request from any http verb';
});

//路由重定向 (Redirect)
Route::redirect('/here','/there');
//路由重定向到指定route
Route::get('/', function(){
  return redirect()->route('route_name');
});

//帶參數重定向到指定route
Route::get('/{id}', function(){
  return redirect()->route('profile', [$id]); //例子1
  return redirect()->route('profile', ['id' => 1]); //例子2
});

//重定向到指定controller
Route::get('/', function(){
  return redirect()->action('yourController@functionA');
});

//帶參數重定向到指定controller
Route::get('/{id}', function(){
  return redirect()->action('yourController@functionA',['id' => 1]);
});

//定義route_name的例子
Route::get('/login', function(){
  return view('login');
})->name('route_name');

//賦予值
//view('name') 即是開啟 resource/views/name.blade.php
Route::get('/', function(){
  return view('welcome', ['website' => 'content_here']);
});
//resources/views/welcome.blade.php 內的 {{$website}} 便會變成 'content_here'

//帶參數
Route::get('user/{id}', function($id){
  return 'User ' . $id;
});

//帶參數到controller
Route::get('user/{id}','UserController@update');
//對應的Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
  public function update(Request $request, $id){
     //do something
  }
}

//帶多個參數
Route::get('posts/{post}/comments/{comment}', function($postId, $commentId){
  return $postId . '-' . $commentId;
});

//可選參數 (在參數名後加一個"?", 所以需要給予變量指定默認值)
Route::get('user/{name?}', function($name = null){
  return $name;
});

//正規約束
Route::get('user/{name}', function($name){
  //$name必須是字母且不能為空
})->where('name', '[A-Za-z]+');

Route::get('user/{id}', function($id){
  //$id必須是數字
})->where('id', '[0-9+');

Route::get('user/{id}/{name}', function($id, $name){
  //同時指定 id 和 name的格式
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
?>

//全域約束 (需要在RouteServiceProvider內的boot function定義)
//位置在 /app/Providers/RouteServiceProvider.php
//一旦定義後 所有id 需要是數字才會有效
public function boot()
{
    Route::pattern('id', '[0-9]+'); //加上這一行
    parent::boot();
}

開始在上面輸入您的搜索詞,然後按回車進行搜索。按ESC取消。

返回頂部