我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
当前回答
这取决于您是想在之后使用用户,还是只检查是否存在一个用户。
如果用户对象存在,你想使用它:
$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
}
其他回答
如果你想在数据库中插入一条记录,而相同邮件的记录不存在,那么你可以这样做:
$user = User::updateOrCreate(
['email' => Input::get('email')],
['first_name' => 'Test', 'last_name' => 'Test']
);
updateOrCreate方法的第一个参数列出了唯一标识关联表中的记录的列,而第二个参数由要插入或更新的值组成。
你可以在这里查看文档:Laravel upserts doc
if($user->isEmpty()){
// has no records
}
Eloquent使用集合。 参见以下链接:https://laravel.com/docs/5.4/eloquent-collections
$user = User::where('email', request('email'))->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');
在if语句中检查null可以防止Laravel在查询结束后立即返回404。
if ( User::find( $userId ) === null ) {
return "user does not exist";
}
else {
$user = User::find( $userId );
return $user;
}
如果找到用户,它似乎会运行双重查询,但我似乎找不到任何其他可靠的解决方案。
在laravel雄辩中,有默认的exists()方法,参考下面的例子。
if (User::where('id', $user_id )->exists()) {
// your code...
}