Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
Laravel 8 自定义登录:将默认邮箱认证改为用户名认证_创想鸟

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

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

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

前言

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

理解 Laravel 认证机制

Laravel 的认证功能主要通过 IlluminateFoundationAuthAuthenticatesUsers 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.phpuse IlluminateDatabaseMigrationsMigration;use IlluminateDatabaseSchemaBlueprint;use IlluminateSupportFacadesSchema;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 模型 (AppModelsUser) 在 $fillable 数组中包含了 name 字段,以便在注册时可以批量赋值。

// app/Models/User.phpnamespace AppModels;use IlluminateContractsAuthMustVerifyEmail;use IlluminateDatabaseEloquentFactoriesHasFactory;use IlluminateFoundationAuthUser as Authenticatable;use IlluminateNotificationsNotifiable;use LaravelSanctumHasApiTokens;class User extends Authenticatable{    use HasApiTokens, HasFactory, Notifiable;    // use HighIdeasUsersOnlineTraitsUsersOnlineTrait; // 如果您使用了此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 示例:

@section('content')
{{ __('Login') }}
@csrf
@error('name') {{ $message }} @enderror
@error('password') {{ $message }} @enderror
@if (Route::has('password.request')) {{ __('Forgot Your Password?') }} @endif
@endsection

register.blade.php 示例:

@section('content')
{{ __('Register') }}
@csrf
@error('name') {{ $message }} @enderror
@error('password') {{ $message }} @enderror
@endsection

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

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

// app/Http/Controllers/Auth/LoginController.phpnamespace AppHttpControllersAuth;use AppHttpControllersController;use AppProvidersRouteServiceProvider;use IlluminateFoundationAuthAuthenticatesUsers;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 的认证系统更加灵活,能够适应不同的业务需求。请务必在进行此类更改后,对登录和注册功能进行全面的测试,以确保一切正常工作。

以上就是Laravel 8 自定义登录:将默认邮箱认证改为用户名认证的详细内容,更多请关注php中文网其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1329628.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
PHP函数类型声明使用_PHP7+函数参数与返回值类型约束设置
上一篇 2025年12月12日 15:48:36
优化多语言网站SEO:避免自动语言重定向对爬虫的影响
下一篇 2025年12月12日 15:48:49

相关推荐

发表回复

登录后才能评论
关注微信