您的位置:首页 > 编程语言 > PHP开发

Laravel5路由筆記

2015-04-11 18:35 330 查看

Laravel5路由筆記

記錄一下Laravel的路由。在laravel中路由順序是按先後而定。請參考here,或here

定義路由

訪問http://domain/

Route::get('/', function(){
return view('index');
});


訪問http://domain/home/

Route::get('home', function(){
return view('home');
});


有參數的訪問http://domain/news/1, http://domain/new/a

Route::get('news/{id}', function($id){
return 'News:'.$id);
});


限制id只能是數字,但是如果要所有的id都必須是數字。

Route::get('news/{id}', function($id){
return 'News:'.$id;
})->where('id','[0-9]+');


若是每條id都限制只能是數字,則會使用:

Route::pattern('id', '[0-9]+');


然後放在最前面,這樣一來就不用每條都設定。

限制路由參數為字母。

Route::get('user/{name}', function($name){
return 'News:'.$id;
})->where('name','[A-Za-z]+');


路徑中只能是數字

Route::get('news/(:num)', function($id){
return 'News:'.$id;
});


路徑中可以是數字、字串

Route::get('news/(:any)', function($id){
return 'News:'.$id;
});


有選擇性默認值的參數路由。

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


數組路由參數並限定id為數字, name為字母

Route::get('user/{id}/{name}', function($id, $name){
return $name.$id;
})->where(array('id'=>'[0-9]+', 'name'=>'[A-Za-z]+'));




Route::get('user/{id}/{name}', function($id, $name){
return $name.$id;
})->where(['id'=>'[0-9]+', 'name'=>'[A-Za-z]+']);


命名路由

使用as的陣列來指定路由名稱

Route::get('user/profile',['as'=>'profile',function()
{
//
}]);


為控制器指定路由名稱

Route::get('user/profile',['as'=>'profile','uses'=>'UserController@ShowProfile']);


路由群組

針對不同的群組套用篩選功能

Route::group(['middleware'=>'auth'],function()
{
Route::get('/',function()
{
// For Auth Filter
});
Route::get('user/profile',function()
{
// For Profile Filter
});
});


在group中使用namespace參數:

Route::group(['namespace'=>'Admin'],function()
{
//
});


路由前綴

使用prefix選項:

Route::group(['prefix'=>'admin'],function()
{
Route::get('user',function()
{
//
});
});


路由控制器

避免每個路由重覆定義,除了群組可用外,還可以應用控制路由。

Route::controller('/','HomeController');


當然在控制器得加入方法來取得視圖。

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class HomeController extends Controller {
/**
* show index 。
*
* @return Response
*/
public function getIndex()
{
return view('home');
}

/**
* show about
*
* @return Response
*/
public function getAbout()
{
return view('about');
}
}


路由資源

Laravel5遵循著RESTful架構規範,通過命令輸入

php artisan make:controller ArticleController


將會產生app/http/Controllers/ArticleController.php,開啟後,里面有寫好的index, create, show等方法。接著只要在app/http/route.php中定義:

Route::resource('article','ArticleController');


那麼只要訪問了/article,路由就有不同的訪問方法了。請參考下表:

請求方法URL請求對應控制方法意義
GET/articleindex索引列表
POST/articlestore建立數據存儲
PUT/PATCH/article/{id}save保存編輯id數據
GET/article/createcreate建立表單
GET/article/{id}show對應id表單顯示
GET/article/{id}/editedit編輯表單
GET/article/{id}destory刪除
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  laravel5 route 路由