我刚来拉拉维尔。如何查找是否存在记录?
$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;
}
如果找到用户,它似乎会运行双重查询,但我似乎找不到任何其他可靠的解决方案。
其他回答
简单,舒适和易于理解的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);
}
要知道是否有记录是很简单的
$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";
if (User::where('email', 'user@email.com')->first()) {
// It exists
} else {
// It does not exist
}
如果只需要检查是否存在,请使用first(),而不要使用count()。
First()更快,因为它检查单个匹配,而count()计数所有匹配。
你已经看到了很多解决方案,但是神奇的检查语法可以是这样的,
$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 (isset(User::where('email', Input::get('email'))->value('email')))
{
// Input::get('email') exist in the table
}