我刚来拉拉维尔。如何查找是否存在记录?

$user = User::where('email', '=', Input::get('email'));

我能做什么来查看$user是否有记录?


当前回答

最短工作选项:

// if you need to do something with the user 
if ($user = User::whereEmail(Input::get('email'))->first()) {

    // ...

}

// otherwise
$userExists = User::whereEmail(Input::get('email'))->exists();

其他回答

if ($u = User::where('email', '=', $value)->first())
{
   // do something with $u
   return 'exists';
} else {
  return 'nope';
}

可以用try/catch吗

->get()仍然返回一个空数组

这取决于您是想在之后使用用户,还是只检查是否存在一个用户。

如果用户对象存在,你想使用它:

$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
   // user doesn't exist
}

如果你只是想检查一下

if (User::where('email', '=', Input::get('email'))->count() > 0) {
   // user found
}

或者更好

if (User::where('email', '=', Input::get('email'))->exists()) {
   // user found
}

我解决了这个问题,使用empty()函数:

$user = User::where('email', Input::get('email'))->get()->first();
//for example:
if (!empty($user))
    User::destroy($user->id);
$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif
if (User::where('email', Input::get('email'))->exists()) {
    // exists
}