Laravel 中间件授权组不工作

Laravel Middleware Auth Group is not working

美好的一天。我的身份验证有问题,我总是将其重定向回登录页面。我发现当我使用下面的代码添加 routes/web.php 时

Route::group(['middleware' => 'auth'], function() {

}

页面总是重定向回登录页面。但是当我删除上面的代码时,我可以进入主页。我想知道如何解决这个问题。我在过去的项目中使用了路由组,我对此没有任何问题。

更新:我使用 php artisan 测试并重新修改了我的 ExampleTest.php 代码。

<?php

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;
use App\User;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $this->assertTrue(true);
    }

    public function testApplication()
    {
        $user = factory(User::class)->create();

        $response = $this->actingAs($user)
                         ->withSession(['foo' => 'bar'])
                         ->get('/');
    }
}

这些是结果

C:\xampp\htdocs\nuadu_helpdesk\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:273
    269|      */
    270|     protected function getRawAttributes(array $attributes = [])
    271|     {
    272|         if (! isset($this->definitions[$this->class])) {
  > 273|             throw new InvalidArgumentException("Unable to locate factory for [{$this->class}].");
    274|         }
    275|
    276|         $definition = call_user_func(
    277|             $this->definitions[$this->class],

  1   C:\xampp\htdocs\nuadu_helpdesk\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:296
      Illuminate\Database\Eloquent\FactoryBuilder::getRawAttributes([])

  2   C:\xampp\htdocs\nuadu_helpdesk\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\GuardsAttributes.php:155
      Illuminate\Database\Eloquent\FactoryBuilder::Illuminate\Database\Eloquent\{closure}()

在 routes.php 文件中,您没有写重定向的位置。所以请像下面这样添加..

Route::group(['middleware' => 'auth'], function() {
  return redirect('/');  //by default you can change it as your requirments.
}

我发现了我的问题。我检查了使用 auth 和 dd。我对 user_id 使用了不同的主键,它是一个字符串类型。我忘了在我的 user.php

中声明它
protected $primaryKey = 'user_id';
protected $keyType = 'string';
public $incrementing = false;

默认情况下,主键始终是 id。如果你声明了一个不同的列名作为你的主键,不要忘记声明我上面所说的代码,否则你将无法读取授权或无法登录。