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

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

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


当前回答

如果你想在数据库中插入一条记录,而相同邮件的记录不存在,那么你可以这样做:

$user = User::updateOrCreate(
    ['email' => Input::get('email')],
    ['first_name' => 'Test', 'last_name' => 'Test']
);

updateOrCreate方法的第一个参数列出了唯一标识关联表中的记录的列,而第二个参数由要插入或更新的值组成。

你可以在这里查看文档:Laravel upserts doc

其他回答

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

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

$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
}

最好的解决方案之一是使用firstOrNew或firstOrCreate方法。文档中有更多关于这两者的详细信息。

if (User::where('email', 'user@email.com')->first()) {
    // It exists
} else {
    // It does not exist
}

如果只需要检查是否存在,请使用first(),而不要使用count()。

First()更快,因为它检查单个匹配,而count()计数所有匹配。

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

if (User::where('email', $request->email)->exists()) {
   //email exists in user table
}

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

像这样检查结果,

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

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