Laravel 登录和注册:验证邮箱
在Laravel框架中,要实现登录和注册时验证邮箱,你需要使用Laravel提供的内置认证系统和Laravel Breeze。以下是实现这一功能的步骤和示例代码:
- 安装Laravel Breeze:
composer require laravel/breeze --dev
php artisan breeze:install
npm install
npm run dev
- 修改用户模型(
User
模型)以确保email_verified_at
字段被用于标记邮箱是否已验证。
在 User
模型中(通常位于 app/Models/User.php
),确保你有以下方法:
// 使用 Laravel 8 或以上版本
use Illuminate\Contracts\Auth\MustVerifyEmail;
class User extends Authenticatable implements MustVerifyEmail
{
// ...
}
- 修改注册控制器以使用
ValidatesEmails
trait,并调用validated
方法后进行邮箱验证。
在注册控制器中(通常位于 app/Http/Controllers/Auth/RegisterController.php
),使用以下代码:
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
class RegisterController extends Controller
{
// ...
protected $redirectTo = RouteServiceProvider::HOME;
public function store(Request $request)
{
$request->validate([
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:8',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
if ($request->wantsJson()) {
return response()->json([], 201);
}
return redirect(RouteServiceProvider::HOME);
}
public function verify(EmailVerificationRequest $request)
{
if ($request->user()->hasVerifiedEmail()) {
return redirect($this->redirectPath());
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return re
评论已关闭