如何在 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'] = "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
廣告