laravel 类 Illuminate\Support\Collection 的对象无法转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45275823/
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\Support\Collection could not be converted to int
提问by
I have condition in Controller with checks the value in database and based on this value is redirecting user to different login pages
我在控制器中有条件检查数据库中的值,并根据此值将用户重定向到不同的登录页面
public function getLogin()
{
$login = DB::table('login')->pluck('login');
//var_dump($login);
if ($login == 1) {
return View::make('users.login');
} else {
return View::make('users.login1');
}
}
When I go to login page I've got this error
当我进入登录页面时出现此错误
Object of class Illuminate\Support\Collection could not be converted to int
类 Illuminate\Support\Collection 的对象无法转换为 int
When I var_dump($login);
I get
当var_dump($login);
我得到
object(Illuminate\Support\Collection)#304 (1) { ["items":protected]=> array(1) { [0]=> int(1) } }
How can I fix this error?
我该如何解决这个错误?
采纳答案by Maraboc
You can use it like this :
你可以这样使用它:
public function getLogin()
{
$login = DB::table('login')->pluck('login');
//var_dump($login);
if ($login->count() == 1) {
return View::make('users.login');
} else {
return View::make('users.login1');
}
}
回答by Onix
$login is a collection, you get all the values of table login with your query. if you want this create a for loop and have your if statement inside.
$login 是一个集合,您可以通过查询获得表登录的所有值。如果你想要这创建一个 for 循环并在里面有你的 if 语句。
for example :
例如 :
foreach ($login as $val) {
if ($val== 1) {
return View::make('users.login');
} else {
return View::make('users.login1');
}
}
回答by Alexey Mezenin
You should use isEmpty()
or count()
here, for example:
您应该在此处使用isEmpty()
或count()
,例如:
if (!$login->isEmpty())
if (count($login) > 0)
if ($login->count() > 0)
回答by Abdullah Manzoor
Ok Its just simple in this case, You can use [0] with login to access it as int.
好的,在这种情况下它很简单,您可以使用 [0] 登录以作为 int 访问它。
public function getLogin()
{
$login = DB::table('login')->pluck('login');
//var_dump($login);
if ($login[0] == 1) {
return View::make('users.login');
} else {
return View::make('users.login1');
}
}