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

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

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


当前回答

简单地用这个来判断真假 $ user =用户::(“电子邮件”、“=”,输入::('邮件'))- >存在(); 如果你想要$user with result,你可以使用这个, $ user =用户::(“电子邮件”、“=”,输入::('邮件'))- > ();

像这样检查结果,

if(count($user)>0){}

你也可以用这个, $ user =用户::(“电子邮件”、“=”,输入::('邮件')); 如果存在($ user - > ()) { $user = $user->get(); }

其他回答

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

$user = User::where('email', Input::get('email'))->get()->first();
//for example:
if (!empty($user))
    User::destroy($user->id);

我认为下面的方法是达到同样目的的最简单的方法:

    $user = User::where('email', '=', $request->input('email'))->first();
    if ($user) {
       // user exist!
    }else{
       // user does not exist
    }

这将检查用户表中是否存在所请求的电子邮件:

if (User::where('email', $request->email)->exists()) {
   //email exists in user table
}
$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif

如果你想插入一个唯一的记录,你可以使用laravel验证:

$validated = $request->validate([
    'title' => 'required|unique:usersTable,emailAddress|max:255',
]);

但是你也可以用这些方法:

1:

if (User::where('email',  $request->email)->exists())
{
  // object exists
} else {
  // object not found
}

2:

$user = User::where('email',  $request->email)->first();

if ($user)
{
  // object exists
} else {
  // object not found
}

3:

$user = User::where('email',  $request->email)->first();

if ($user->isNotEmpty())
{
  // object exists
} else {
  // object not found
}

4:

$user = User::where('email',  $request->email)->firstOrCreate([
      'email' => 'email'
],$request->all());