我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
当前回答
我解决了这个问题,使用empty()函数:
$user = User::where('email', Input::get('email'))->get()->first();
//for example:
if (!empty($user))
User::destroy($user->id);
其他回答
if (User::where('email', Input::get('email'))->exists()) {
// exists
}
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
可以写成
if (User::where('email', '=', Input::get('email'))->first() === null) {
// user doesn't exist
}
这将返回true或false,而不分配临时变量,如果这是你在原始语句中使用$user的全部目的。
if (User::where('email', 'user@email.com')->first()) {
// It exists
} else {
// It does not exist
}
如果只需要检查是否存在,请使用first(),而不要使用count()。
First()更快,因为它检查单个匹配,而count()计数所有匹配。
$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif
if ($u = User::where('email', '=', $value)->first())
{
// do something with $u
return 'exists';
} else {
return 'nope';
}
可以用try/catch吗
->get()仍然返回一个空数组