我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
当前回答
简单,舒适和易于理解的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);
}
其他回答
$userCnt = User::where("id",1)->count();
if( $userCnt ==0 ){
//////////record not exists
}else{
//////////record exists
}
注:其中条件根据您的要求。
你已经看到了很多解决方案,但是神奇的检查语法可以是这样的,
$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
这取决于您是想在之后使用用户,还是只检查是否存在一个用户。
如果用户对象存在,你想使用它:
$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::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
可以写成
if (User::where('email', '=', Input::get('email'))->first() === null) {
// user doesn't exist
}
这将返回true或false,而不分配临时变量,如果这是你在原始语句中使用$user的全部目的。
if ($u = User::where('email', '=', $value)->first())
{
// do something with $u
return 'exists';
} else {
return 'nope';
}
可以用try/catch吗
->get()仍然返回一个空数组