当前位置:首页 > 文章列表 > 文章 > php教程 > Laravel8自定义登录:用用户名代替邮箱

Laravel8自定义登录:用用户名代替邮箱

2025-11-07 20:15:35 0浏览 收藏

想要在 Laravel 8 中实现更灵活的用户登录认证?本教程将教你如何轻松将默认的邮箱登录改为用户名登录。Laravel 默认使用 email 字段进行用户认证,但通过修改 `LoginController` 中的 `username()` 方法,你可以指定 `name` 字段作为登录凭据。本文详细讲解了修改数据库结构、更新视图文件以及重写 `username()` 方法的关键步骤,助你快速实现基于用户名的 Laravel 8 自定义登录功能,提升用户体验和安全性。赶快来学习 Laravel 8 用户名登录认证的技巧吧!

Laravel 8 自定义登录:将默认邮箱认证改为用户名认证

本教程详细介绍了如何在 Laravel 8 应用程序中,将默认的用户登录认证机制从使用邮箱改为使用用户名。核心步骤是通过重写 `LoginController` 中的 `username()` 方法,指定以 `name` 字段作为认证凭据,从而实现基于用户名的灵活登录。

前言

Laravel 框架为用户认证提供了强大且开箱即用的支持。默认情况下,Laravel 的认证系统使用用户的 email 字段作为登录凭据。然而,在许多应用场景中,开发者可能需要使用其他字段,例如 username(或 name)来进行用户登录。本教程将指导您如何在 Laravel 8 项目中,轻松地将默认的邮箱认证机制修改为基于用户名的认证。

理解 Laravel 认证机制

Laravel 的认证功能主要通过 Illuminate\Foundation\Auth\AuthenticatesUsers Trait 实现。这个 Trait 包含了处理用户登录、注销等逻辑的核心方法。其中,决定登录凭据字段的关键方法是 username()。默认情况下,此方法返回 'email',指示系统使用 email 字段进行认证。

如果您在 login.blade.php 视图文件中将登录字段从 email 修改为 name,但未在控制器层面进行相应配置,系统仍会尝试使用 email 进行认证,导致登录失败。

修改登录认证字段的步骤

要将登录认证字段从 email 切换到 name,我们需要进行以下调整:

1. 确认数据库结构与用户模型

首先,请确保您的 users 表中包含一个用于用户名的字段,例如 name,并且该字段应具备唯一性约束,以避免登录冲突。

// database/migrations/xxxx_xx_xx_xxxxxx_create_users_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable()->unique(); // 确保 'name' 字段存在且唯一
            $table->string('education')->nullable();
            $table->string('sponsor')->nullable();
            $table->string('telegram')->unique();
            $table->boolean('is_admin')->default(0);
            $table->text('skills')->nullable();
            $table->boolean('is_deleted')->default(0);
            $table->boolean('is_verified')->default(0);
            $table->boolean('is_banned')->default(0);
            $table->integer('rank')->default(0);         
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

同时,确保您的 User 模型 (App\Models\User) 在 $fillable 数组中包含了 name 字段,以便在注册时可以批量赋值。

// app/Models/User.php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    // use \HighIdeas\UsersOnline\Traits\UsersOnlineTrait; // 如果您使用了此Trait,请保留

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name', // 确保 'name' 在可填充字段中
        'password',
        'skills',
        'education',
        'sponsor',
        'telegram',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    // ... 其他方法
}

2. 更新登录和注册视图文件

接下来,您需要修改登录表单视图 (resources/views/auth/login.blade.php) 和注册表单视图 (resources/views/auth/register.blade.php),将用于输入登录凭据的 input 字段的 name 属性从 email 更改为 name。

login.blade.php 示例:

<!-- resources/views/auth/login.blade.php -->

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Login') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('login') }}">
                        @csrf

                        <div class="form-group row">
                            <label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Username') }}</label>

                            <div class="col-md-6">
                                &lt;input id=&quot;name&quot; type=&quot;text&quot; class=&quot;form-control @error(&apos;name&apos;) is-invalid @enderror&quot; name=&quot;name&quot; value=&quot;{{ old(&apos;name&apos;) }}&quot; required autocomplete=&quot;name&quot; autofocus&gt;

                                @error('name')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>

                            <div class="col-md-6">
                                &lt;input id=&quot;password&quot; type=&quot;password&quot; class=&quot;form-control @error(&apos;password&apos;) is-invalid @enderror&quot; name=&quot;password&quot; required autocomplete=&quot;current-password&quot;&gt;

                                @error('password')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <!-- ... 其他表单元素,如“记住我”和“忘记密码”链接 -->

                        <div class="form-group row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Login') }}
                                </button>

                                @if (Route::has('password.request'))
                                    <a class="btn btn-link" href="{{ route('password.request') }}">
                                        {{ __('Forgot Your Password?') }}
                                    </a>
                                @endif
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

register.blade.php 示例:

<!-- resources/views/auth/register.blade.php -->

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Register') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('register') }}">
                        @csrf

                        <div class="form-group row">
                            <label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Username') }}</label>

                            <div class="col-md-6">
                                &lt;input id=&quot;name&quot; type=&quot;text&quot; class=&quot;form-control @error(&apos;name&apos;) is-invalid @enderror&quot; name=&quot;name&quot; value=&quot;{{ old(&apos;name&apos;) }}&quot; required autocomplete=&quot;name&quot; autofocus&gt;

                                @error('name')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <!-- ... 其他注册字段,如 telegram, skills, education, sponsor -->

                        <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>

                            <div class="col-md-6">
                                &lt;input id=&quot;password&quot; type=&quot;password&quot; class=&quot;form-control @error(&apos;password&apos;) is-invalid @enderror&quot; name=&quot;password&quot; required autocomplete=&quot;new-password&quot;&gt;

                                @error('password')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>

                            <div class="col-md-6">
                                &lt;input id=&quot;password-confirm&quot; type=&quot;password&quot; class=&quot;form-control&quot; name=&quot;password_confirmation&quot; required autocomplete=&quot;new-password&quot;&gt;
                            </div>
                        </div>

                        <div class="form-group row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Register') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

3. 重写 LoginController 中的 username() 方法

这是实现自定义登录字段的核心步骤。您需要在 App\Http\Controllers\Auth\LoginController 中重写 AuthenticatesUsers Trait 提供的 username() 方法。

// app/Http/Controllers/Auth/LoginController.php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * 获取用于控制器登录的用户名字段。
     *
     * @return string
     */
    public function username()
    {
        return 'name'; // 将默认的 'email' 更改为 'name'
    }
}

通过添加上述 username() 方法并使其返回 'name',您就指示了 Laravel 认证系统在尝试登录时,使用表单中提交的 name 字段值与数据库中的 name 字段进行匹配,而不是默认的 email 字段。

注意事项

  • 字段唯一性: 确保您选择的登录字段(例如 name)在数据库中是唯一的,否则可能会导致认证失败或意外行为。在提供的迁移文件中,name 字段已设置为 unique(),这符合要求。
  • 注册流程: 如果您也修改了注册表单,确保注册逻辑(例如 RegisterController)能够正确处理新的用户名字段。在本教程提供的原始数据中,注册表单也使用了 name 字段,因此注册流程通常不会受到影响。
  • 其他自定义: 如果您需要更复杂的自定义登录逻辑,例如同时支持邮箱和用户名登录,您可能需要进一步重写 AuthenticatesUsers Trait 中的 credentials() 方法,在该方法中根据用户输入判断是邮箱还是用户名。

总结

通过简单地在 LoginController 中重写 username() 方法,您可以轻松地将 Laravel 应用程序的默认登录凭据从 email 切换到任何您需要的字段,例如 name。这一改动使得 Laravel 的认证系统更加灵活,能够适应不同的业务需求。请务必在进行此类更改后,对登录和注册功能进行全面的测试,以确保一切正常工作。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Laravel8自定义登录:用用户名代替邮箱》文章吧,也可关注golang学习网公众号了解相关技术文章。

哔哩哔哩青少年模式怎么设置哔哩哔哩青少年模式怎么设置
上一篇
哔哩哔哩青少年模式怎么设置
通义千问官网最新入口及访问指南
下一篇
通义千问官网最新入口及访问指南
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    543次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    516次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    500次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    485次学习
查看更多
AI推荐
  • ChatExcel酷表:告别Excel难题,北大团队AI助手助您轻松处理数据
    ChatExcel酷表
    ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
    3180次使用
  • Any绘本:开源免费AI绘本创作工具深度解析
    Any绘本
    探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
    3391次使用
  • 可赞AI:AI驱动办公可视化智能工具,一键高效生成文档图表脑图
    可赞AI
    可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
    3420次使用
  • 星月写作:AI网文创作神器,助力爆款小说速成
    星月写作
    星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
    4526次使用
  • MagicLight.ai:叙事驱动AI动画视频创作平台 | 高效生成专业级故事动画
    MagicLight
    MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
    3800次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码