如何在 Laravel 中检查用户电子邮件是否已存在?

laravelphpserver side programming更新于 2025/4/30 0:37:17

有很多方法可以测试电子邮件是否存在。一种方法是使用验证器类。要使用验证器,您需要包含如下所示的类;

use Illuminate\Support\Facades\Validator;

示例 1

该示例展示了如何使用验证器检查电子邮件是否已注册。

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class UserController extends Controller { public function index() { $inputValues['email'] = "heena@gmail.com"; // checking if email exists in ‘email’ in the ‘users’ table $rules = array('email' => 'unique:users,email'); $validator = Validator::make($inputValues, $rules); if ($validator->fails()) { echo 'The email already exists'; } else { echo 'The email is not registered'; } } }

输出

上述代码的输出是 −

The email already exists

示例 2

现在让我们尝试使用用户表中不存在的电子邮件。

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class UserController extends Controller{ public function index() { $inputValues['email'] = "test@gmail.com"; // checking if email exists in ‘email’ in the ‘users’ table $rules = array('email' => 'unique:users,email'); $validator = Validator::make($inputValues, $rules); if ($validator->fails()) { echo 'The email already exists'; } else { echo 'The email is not registered'; } } }

输出

上述代码的输出是 −

The email is not registered

示例 3

您可以使用 Eloquent 模型来检查用户表中是否存在电子邮件

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller{ public function index() { $email = "heena@gmail.com"; $userEmailDetails = User::where('email', '=', $email)->first(); if ($userEmailDetails === null) { echo 'The email is not registered'; } else { echo 'The email already exists'; } } }

输出

上述代码的输出是 −

The email already exists

示例 4

使用 Laravel eloquent 模型中的 count() 方法 −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index() { $email = "heena@gmail.com"; if (User::where('email', '=', $email)->count() > 0) { echo "Email Exists"; } else { echo "Email is not registered"; } } }

输出

上述代码的输出是 −

Email Exists

示例 5

使用 Laravel eloquent 模型中的 exists() 方法 −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller{ public function index() { $email = "heena@gmail.com"; if (User::where('email', '=', $email)->exists()) { echo "Email Exists"; } else { echo "Email is not registered"; } } }

输出

上述代码的输出是 −

Email Exists

相关文章