类的对象阐明数据库eloquent集合无法转换为int

Dev*_*abi 0 database laravel eloquent

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

protected $casts = [
    'role' => 'integer',
];
Run Code Online (Sandbox Code Playgroud)

这是我的控制器功能,我在其中访问用户角色列值.它返回数组中的值,但我想将它与整数值'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";
    }
}
Run Code Online (Sandbox Code Playgroud)

Vik*_*ode 6

问题

$user = User::where("email",$email)->get(['role']); // <= look here (fetching)

if ($user == 2) { // <= look here (validation)
  return view('admin.dashboard');
}
Run Code Online (Sandbox Code Playgroud)

解决方案

获取对象

// 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(); 
Run Code Online (Sandbox Code Playgroud)

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

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

如果您期望多个记录,您可以使用类似的方法->all(),->get()它们将检索多个结果 - source:laravel docs

验证

此时,$user变量包含一个雄辩的对象,并且无法将对象与整数(int)进行比较.

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

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