【问题标题】:Laravel role based page access - Trying to get property of non-object - Auth::user()Laravel 基于角色的页面访问 - 试图获取非对象的属性 - Auth::user()
【发布时间】:2013-05-31 09:30:48
【问题描述】:

对 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

我的想法取决于用户访问级别,即用户对象中的“级别”,我将过滤页面等。

但是我收到一个错误“尝试获取非对象的属性”,这与此代码有关:

if(Auth::user()->level < 4) {

在视图中测试 Auth::user()->level 确认用户已登录。谁能告诉为什么这在 routes.php 中作为过滤器不起作用?

谢谢

【问题讨论】:

    标签: authentication routes laravel laravel-3


    【解决方案1】:

    问题已解决 - 我在脚本中使用了不正确的语法,我在此处发布后意识到这一点。

    if($user_level = Auth::user()->level < 4) {
    

    应该是:

    if(Auth::user()->level < 4) {
    

    过滤器现在可以工作了。但是我正在寻找改进的方法,因为不确定这是现在最有效的方法!

    谢谢

    【讨论】:

      猜你喜欢
      • 2018-03-07
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      相关资源
      最近更新 更多