最近在使用Entrust這個Laravel的套件,其中預設permission表格中有個「name」是用來表示這個permission的功能,在Entrust中是唯一值。然後後來我將其用來記錄user目前欲執行的action,例如說user只有「讀取」product資料的功能,但沒有「編輯」的功能,在url顯示上會是如下(PS:Route定義product為controller,使用RESTful的定義)
A:讀取id為65的product資料,可正常執行:
1 |
http://mydomain.com/product/65 |
B:但沒有編輯product的權限,不可執行:
1 |
http://mydomain.com/product/65/edit |
我的想法是,我只要知道目前的user在作什麼事,再到permissions中去找是否有此權限即可,故我需要取得目前user正在執行的事情,可用方法如下:
1 |
$action = Route::currentRouteAction(); |
即可取得目前的action,故A是:
1 |
ProductController@index |
而B是:
1 |
ProductController@edit |
然後將其定義在permissions表中的name,像下面這樣你有很多個action:
然後配合Entrust中的「can」使用,即可完全過濾沒有該權限的user:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//取得目前的controller ex: menus* $p_str_controllerName = Request::segment(1); if( !empty($p_str_controllerName) ) { //目前執行的網址 ex: menus* $p_str_currentUrl = $p_str_controllerName."*"; Route::filter('action_filter', function() { //目前user的動作 permissions.name = action $p_str_controllerAction = Route::currentRouteAction(); if(!Entrust::can($p_str_controllerAction) ) return Redirect::to('/'); }); Route::when( $p_str_currentUrl, 'action_filter'); } |
如果需要取得目前route的名字的話,可以使用這個:
1 |
Route::currentRouteName(); |
另外,如果在view中需的話如下:
controller name
1 |
{{ substr(Route::currentRouteAction(), 0, (strpos(Route::currentRouteAction(), '@') -0) ) }} |
action name
1 |
{{ substr(Route::currentRouteAction(), (strpos(Route::currentRouteAction(), '@') + 1)) }} |