You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 11+Breeze实现手机号/邮箱登录:LoginRequest.php修改

在Laravel 11 Breeze中实现手机号/邮箱登录

1. 调整LoginRequest的验证规则

替换默认的email字段验证,改为针对「邮箱或手机号」字段(假设你的表单输入框name为login)的自定义验证:

// app/Http/Requests/Auth/LoginRequest.php
public function rules(): array
{
    return [
        'login' => [
            'required',
            'string',
            function ($attribute, $value, $fail) {
                // 验证是否为邮箱或符合规则的手机号(这里用国内手机号正则,可按需修改)
                $isEmail = filter_var($value, FILTER_VALIDATE_EMAIL);
                $isPhone = preg_match('/^1[3-9]\d{9}$/', $value);
                
                if (!$isEmail && !$isPhone) {
                    $fail('请输入有效的邮箱或手机号');
                }
            }
        ],
        'password' => ['required', 'string'],
    ];
}

2. 修改认证逻辑

重写authenticate()方法,根据输入内容判断是邮箱还是手机号,再执行认证:

// app/Http/Requests/Auth/LoginRequest.php
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

public function authenticate(): void
{
    $this->ensureIsNotRateLimited();

    // 判断输入的是邮箱还是手机号(假设数据库手机号字段为`phone`)
    $loginField = filter_var($this->login, FILTER_VALIDATE_EMAIL) ? 'email' : 'phone';

    // 执行认证
    if (!Auth::attempt(
        [$loginField => $this->login, 'password' => $this->password],
        $this->boolean('remember')
    )) {
        RateLimiter::hit($this->throttleKey());

        throw ValidationException::withMessages([
            'login' => trans('auth.failed'),
        ]);
    }

    RateLimiter::clear($this->throttleKey());
}

3. 调整限流键(Throttle Key)

默认限流基于email字段,现在改为用login字段,重写throttleKey()方法:

// app/Http/Requests/Auth/LoginRequest.php
use Illuminate\Support\Str;

protected function throttleKey(): string
{
    return Str::transliterate(Str::lower($this->input('login')) . '|' . $this->ip());
}

4. 表单视图对应调整

确保登录表单里的输入框name为login,标签改为「邮箱或手机号」:

<!-- resources/views/auth/login.blade.php -->
<div>
    <x-input-label for="login" :value="__('邮箱或手机号')" />
    <x-text-input id="login" class="block mt-1 w-full" type="text" name="login" :value="old('login')" required autofocus autocomplete="username" />
    <x-input-error :messages="$errors->get('login')" class="mt-2" />
</div>

注意事项

  • 如果数据库中手机号字段不是phone,请将代码中的phone替换为实际字段名
  • 手机号正则可根据业务需求调整(比如支持国际手机号)
  • 确保用户表中已存在手机号字段,且已完成数据库迁移

内容的提问来源于stack exchange,提问作者zockchin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 07:16:08