我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
当前回答
你已经看到了很多解决方案,但是神奇的检查语法可以是这样的,
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
当没有找到任何相关模型时,它会自动引发一个响应404的异常,有时你可能希望在没有找到模型时抛出一个异常。这在路由或控制器中特别有用。fingernail和firstOrFail方法将检索查询的第一个结果;但是,如果没有找到结果,则会抛出一个Illuminate\Database\Eloquent\ModelNotFoundException异常。
裁判:https://laravel.com/docs/5.8/eloquent # retrieving-single-models
其他回答
最短工作选项:
// 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();
如果你想在数据库中插入一条记录,而相同邮件的记录不存在,那么你可以这样做:
$user = User::updateOrCreate(
['email' => Input::get('email')],
['first_name' => 'Test', 'last_name' => 'Test']
);
updateOrCreate方法的第一个参数列出了唯一标识关联表中的记录的列,而第二个参数由要插入或更新的值组成。
你可以在这里查看文档:Laravel upserts doc
$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif
这是一个简单的代码来检查电子邮件是否存在数据库
$data = $request->all(); $user = DB::table('User')->pluck('email')->toArray(); if(in_array($user,$data['email'])) { echo 'existed email'; }
if (User::where('email', Input::get('email'))->exists()) {
// exists
}