如何在 Laravel 中检查用户电子邮件是否存在?
有多种方法可以测试电子邮件是否存在。一种方法是使用校验器类。为了使用校验器,你需要像下面这样包含类;
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'] = "[email protected]"; // 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'] = "[email protected]"; // 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 = "[email protected]"; $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 = "[email protected]"; 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 = "[email protected]"; if (User::where('email', '=', $email)->exists()) { echo "Email Exists"; } else { echo "Email is not registered"; } } }
输出
上述代码的输出为 -
Email Exists
广告