Laravel 3仍然是一个非常新的并且正在处理一些问题。
我正在尝试设置基于角色的页面访问权限。用户目前能够登录并且该部分运行良好,但我想根据用户角色限制对某些页面的访问,例如管理员,编辑等。
所以,我已经创建了一个过滤器,如下所示:
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
的教程我的想法取决于用户访问级别,这是级别&#39;在用户对象中我过滤页面等。
然而,我收到错误并试图获取非对象的属性&#39;这与此代码有关:
if(Auth::user()->level < 4) {
在视图中测试Auth :: user() - &gt;级别确认用户已登录。任何人都可以建议为什么这在routes.php中不能作为过滤器工作?
谢谢
答案 0 :(得分:1)
问题解决了 - 我在我的脚本中使用了错误的语法,我在这里发布了这个语法。
if($user_level = Auth::user()->level < 4) {
应该是:
if(Auth::user()->level < 4) {
过滤器现在可以使用了。但是我正在寻找改进的方法,因为不确定这是现在最有效的方式!
由于