我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
当前回答
在if语句中检查null可以防止Laravel在查询结束后立即返回404。
if ( User::find( $userId ) === null ) {
return "user does not exist";
}
else {
$user = User::find( $userId );
return $user;
}
如果找到用户,它似乎会运行双重查询,但我似乎找不到任何其他可靠的解决方案。
其他回答
if (User::where('email', 'user@email.com')->first()) {
// It exists
} else {
// It does not exist
}
如果只需要检查是否存在,请使用first(),而不要使用count()。
First()更快,因为它检查单个匹配,而count()计数所有匹配。
这取决于您是想在之后使用用户,还是只检查是否存在一个用户。
如果用户对象存在,你想使用它:
$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
}
这是一个简单的代码来检查电子邮件是否存在数据库
$data = $request->all(); $user = DB::table('User')->pluck('email')->toArray(); if(in_array($user,$data['email'])) { echo 'existed email'; }
简单,舒适和易于理解的Validator
class CustomerController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:customers',
'phone' => 'required|string|max:255|unique:customers',
'password' => 'required|string|min:6|confirmed',
]);
if ($validator->fails()) {
return response(['errors' => $validator->errors()->all()], 422);
}
创建下面的方法(为自己),以检查给定的记录id是否存在于Db表中。
private function isModelRecordExist($model, $recordId)
{
if (!$recordId) return false;
$count = $model->where(['id' => $recordId])->count();
return $count ? true : false;
}
// To Test
$recordId = 5;
$status = $this->isModelRecordExist( (new MyTestModel()), $recordId);
有帮助!