laravel 类illuminate 数据库eloquent 集合的对象无法转换为int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43386088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
object of class illuminate database eloquent collection could not be converted to int
提问by DevTaabi
I am accessing the user table attribute 'role' and want to check if role is 2 then show dashboard but getting this error. here is my code
我正在访问用户表属性“角色”并想检查角色是否为 2 然后显示仪表板但收到此错误。这是我的代码
protected $casts = [
'role' => 'integer',
];
here is my controller function where I am accessing the user role column value. it returns the value in array but I want to compare it with an integer value '2'.
这是我的控制器功能,我在其中访问用户角色列值。它返回数组中的值,但我想将它与整数值“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";
}
}
回答by VikingCode
Problem
问题
$user = User::where("email",$email)->get(['role']); // <= look here (fetching)
if ($user == 2) { // <= look here (validation)
return view('admin.dashboard');
}
Solutions
解决方案
Fetching object
获取对象
// 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();
Note: A collection is an object containing other objects
注意:集合是包含其他对象的对象
If email is a unique value, you can use ->first()
to retrieve the first model matching the query constraints - source: laravel docs
如果 email 是唯一值,您可以使用->first()
检索匹配查询约束的第一个模型 -来源:laravel docs
If you expect multiple records, you can use methods like ->all()
and ->get()
which will retrieve multiple results - source: laravel docs
如果您希望有多个记录,您可以使用类似->all()
和->get()
这样的方法来检索多个结果 -来源:laravel docs
Validation
验证
At this point, $user
variable, contains an eloquent object and it's impossible to compare an object with an integer ( int
).
此时,$user
变量包含一个 eloquent 对象,并且不可能将对象与整数 ( int
)进行比较。
What you really want to do: check if the user's role is equaled to 2
你真正想做的:检查用户的角色是否等于2
if ($user->role == 2) { // <= look here
return view('admin.dashboard');
}
回答by linktoahref
Change this line in your code
更改代码中的这一行
$user = User::where("email",$email)->get(['role']);
to this
对此
$user = User::where("email",$email)->first();
as get would return a collection, and then you could check for the user role as
因为 get 会返回一个集合,然后你可以检查用户角色
if ($user->role == 2) {