【问题标题】:Zizaco Entrust 'hasRole' not working within Laravel controllerZizaco Entrust 'hasRole' 在 Laravel 控制器中不起作用
【发布时间】:2014-05-05 12:08:40
【问题描述】:

用户模型:

<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
use Zizaco\Entrust\HasRole;

class User extends Eloquent implements UserInterface, RemindableInterface {

    use HasRole;

角色模型:

<?php

use Zizaco\Entrust\EntrustRole;

class Role extends EntrustRole
{

}

权限模型:

<?php

use Zizaco\Entrust\EntrustPermission;

class Permission extends EntrustPermission
{

}

用户控制器:

public function postSignin(){
        if (Auth::attempt(array('email'=>Input::get('email'),
                                'password'=>Input::get('password')))) {

            $id         = Auth::user()->id;
            $user       = User::where('id','=',$id);
            $firstname = Auth::user()->firstname;

            if ($user->hasRole("User_Not_Approved")) {
                return Redirect::intended('/users/dashboard');
                    }

错误信息:

BadMethodCallException 调用未定义的方法 Illuminate\Database\Query\Builder::hasRole()

当 IF 语句运行时出现错误消息,而用户正在登录。我已按照 Entrust 的说明进行操作,但我不知道为什么它没有使用该方法。

任何帮助将不胜感激!

【问题讨论】:

    标签: laravel laravel-4


    【解决方案1】:

    尝试更改:$user = User::where('id','=',$id);到 $user = User::find($id);

    User::where 需要 ->get 来返回你想要的,即使那样它也会返回一个集合;你会想要像 User::where(etc)->first();以确保您有一个用户实例。但实际上,由于您是通过 id 检索,这就是 ->find($id) 的设计目的,也是您应该做的。

    【讨论】:

    • 澄清一下,->where 正在返回一个查询生成器对象,该对象期望被链接到其他生成器方法,如更多 where()、sum() 等。你必须'使用 ->get() 或 ->first() (将返回集合中的第一个结果)完成您的查询。否则 ->find() 会跳过所有这些,并且是通过主键获取某些内容的最简单方法:)
    • 谢谢你,约翰,这是最有帮助的。你比 Laravel 指南解释得更清楚!它现在是一种享受。再次感谢。
    • 没问题,很高兴能帮上忙!我同意 Laravel 文档最终给我留下的问题多于答案.. 花了一段时间才对事情有正确的感觉。坚持下去,事情就会开始变得更有意义!
    猜你喜欢
    • 1970-01-01
    • 2016-12-04
    • 2018-02-12
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 2015-04-03
    相关资源
    最近更新 更多