【问题标题】:object of class illuminate database eloquent collection could not be converted to int类照亮数据库雄辩集合的对象无法转换为 int
【发布时间】:2017-09-09 05:04:17
【问题描述】:

我正在访问用户表属性“角色”并想检查角色是否为 2,然后显示仪表板但收到此错误。 这是我的代码

protected $casts = [
    'role' => 'integer',
];

这是我访问用户角色列值的控制器函数。它返回数组中的值,但我想将它与整数值“2”进行比较。

public function postSignIn(Request $request)
{
    $this->validate($request,[
        'email' => 'required',
        'password' => 'required',
    ]);
    $posts = Post::all();
    $email = $request['email'];
    $user = User::where("email",$email)->get(['role']);
    if(Auth:: attempt(['email' => $request['email'] , 'password' => $request['password']]))
    {
        if ($user == 2) {
            return view('admin.dashboard');

        }
        else {
            return view('frontend.layouts.user_login_layout', compact('posts'));
        }
    }else{
        return "wrong User";
    }
}

【问题讨论】:

    标签: database laravel eloquent


    【解决方案1】:

    问题

    $user = User::where("email",$email)->get(['role']); // <= look here (fetching)
    
    if ($user == 2) { // <= look here (validation)
      return view('admin.dashboard');
    }
    

    解决方案

    正在获取对象

    // RETURN me FIRST user FROM collection of users WHERE row email EQUALS $email
    $user = User::where("email",$email)->first(); 
    // Better aproach is to fail ( throw exseption ) if collection is empty
    $user = User::where("email",$email)->firstOrFail(); 
    

    注意:集合是包含其他对象的对象

    如果 email 是唯一值,您可以使用 -&gt;first() 检索与查询约束匹配的第一个模型 - source: laravel docs

    如果您期望多条记录,您可以使用-&gt;all()-&gt;get() 之类的方法来检索多个结果 - source: laravel docs

    验证

    此时,$user 变量包含一个 eloquent 对象,无法将对象与整数 (int) 进行比较。

    你真正想做的事:检查用户的角色是否等于2

    if ($user->role == 2) { // <= look here 
       return view('admin.dashboard');
    }
    

    【讨论】:

    • 我已经尝试过了。它显示了一个异常。此集合实例上不存在属性 [角色]。
    • 当我使用 if ($user['role'] == 2) 它显示未定义的索引:角色
    • 您应该使用与数据库中角色“列名”相同的名称。如果找不到,请为您的用户对象提供数据库架构。就像我之前悲伤的那样:$user 是一个对象而不是数组!...你不能像数组一样访问它。
    • Schema::create('users', function (Blueprint $table) { $table->increments('id')->unique(); $table->string('email') ->unique(); $table->string('password'); $table->integer('role'); $table->timestamp('last_login')->nullable(); $table->rememberToken( ); $table->timestamps(); });
    • 我的列名是角色。和我在控制器功能中使用的一样
    【解决方案2】:

    在您的代码中更改此行

    $user = User::where("email",$email)->get(['role']);
    

    到这里

    $user = User::where("email",$email)->first();
    

    因为 get 会返回一个集合,然后您可以检查用户角色为

    if ($user->role == 2) {
    

    【讨论】:

      猜你喜欢
      • 2017-10-24
      • 2019-05-31
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      相关资源
      最近更新 更多