Laravel role based page access - Trying to get property of non-object - Auth::user()
对于Laravel 3还是很新的东西,并解决了一些问题。
我正在尝试建立基于角色的页面访问权限。用户当前可以登录,并且该部分运行良好,但是我想根据用户角色(例如管理员,编辑者等)来限制对某些页面的访问。
因此,我创建了一个过滤器,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | Route::filter('check_roles', function () { $current_url = URI::current(); //get current url excluding the domain. $current_page = URI::segment(2); //get current page which is stored in the second uri segment. Just a refresher: //the first uri segment is the controller, the second is the method, //third and up are the parameters that you wish to pass in $access = 0; $counter = 1; //excluded pages are the pages we don't want to execute this filter //since they should always be accessible for a logged in user $excluded_pages = array( 'base' => array('login', 'user/authenticate'), 1 => array('user/profile', 'dashboard','dashboard/index','articles','articles/index', 'articles/create', 'articles/preview', 'articles/edit', 'user/profile', 'user/logout'), 2 => array('articles/publish','user/create', 'user/edit'), 3 => array('user/delete') ); if (!in_array($current_url, $excluded_pages['base']) ) { //if current page is not an excluded pages if(Auth::user()->level < 4) { do { if (in_array($current_url, $excluded_pages[$counter])) { $access=1; } $counter++; } while ($counter < $user_level AND $counter < 4); if ($access == 0) { //if user doesn't have access to the page that he's trying to access //redirect the user to the homepage return Redirect::to('dashboard') ->with('error', 'You don\'t have permission to access the following page: ' . $current_url); } } } |
这是基于我发现的教程https://gist.github.com/anchetaWern/4223764
我的想法取决于用户访问级别,即我要过滤页面等的用户对象中的\\'level \\'。
但是我遇到错误\\'试图获取非对象的属性\\',这与以下代码有关:
1 | if(Auth::user()->level < 4) { |
在视图中测试Auth :: user()->级别可确认用户已登录。有人可以建议为什么在route.php中作为过滤器不起作用吗?
谢谢
问题已解决-我在脚本中使用了不正确的语法,一旦在此处发布,我就意识到了这一点。
1 | if($user_level = Auth::user()->level < 4) { |
应为:
1 | if(Auth::user()->level < 4) { |
过滤器现在可以使用。但是,我正在寻找改进的方法,因为不确定这是否是目前最有效的方法!
谢谢