首页 > 解决方案 > 使用用户名的 Laravel 身份验证不区分大小写

问题描述

我正在使用 Laravel 手动身份验证,我需要区分大小写的用户名检查,但 laravel 默认情况下不区分大小写检查,我在文档中找不到如何更改它。是否有一些简单的方法或者我需要编写自己的身份验证?

这是我的控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    /**
     * Handle an authentication attempt.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return Response
     */
    public function authenticate(Request $request)
    {
        $credentials = $request->only('username', 'password');

        if (Auth::attempt($credentials)) {

            return redirect()->intended('dashboard');
        }
        return redirect()->intended('login');
    }

标签: phplaravelauthenticationlaravel-7

解决方案


不区分大小写的匹配不是来自 Laravel 本身,而是来自您的数据库,该数据库(在大多数情况下)使用不区分大小写的排序规则来存储用户名。您可以将迁移更改为例如:

 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique()->collation('utf8_bin');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

这会将电子邮件列与utf8_bin不区分大小写的排序规则进行排序。但是,该集合将影响列的排序,因此ORDER BY email如果您使用顺序不明确的 UTF8 字符,任何查询都可能返回不同的顺序。如果这是只能使用 ASCII 字符的电子邮件或用户名,这不是问题。


推荐阅读