在控制器中无法获取用户ID,并且Auth :: check()无法正常工作-Laravel 5.8

iku*_*ris 4 php laravel laravel-5 laravel-5.8

我是laravel 5.8的新手,无法Auth在api控制器中使用,以下为详细信息:

  1. 我已将默认用户表从更改usersUser

User.php

<?php

    namespace App;

    use Illuminate\Notifications\Notifiable;
    use Illuminate\Contracts\Auth\MustVerifyEmail;
    use Illuminate\Foundation\Auth\User as Authenticatable;

    class User extends Authenticatable
    {
        use Notifiable;
        protected $table = 'User';

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'firstName', 'lastName', 'email', 'password',
        ];

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

        /**
         * The attributes that should be cast to native types.
         *
         * @var array
         */
        protected $casts = [
            'email_verified_at' => 'datetime',
        ];
    }
Run Code Online (Sandbox Code Playgroud)
  1. 没有更改auth.php中的任何内容

    <?php 
      return 
    
    ['defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],
    
    
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],
    
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
    
        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],
    
    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ], 
    ];
    
    Run Code Online (Sandbox Code Playgroud)

我的问题:如何使Auth :: check()在此控制器中工作并获取用户ID。这返回Not logged

<?php

namespace App\Http\Controllers\api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use Session;
use DB;
use Response;

use Auth;

class AccountsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {   
         //
        $userID = Auth::id();

        if (Auth::check()) {
            return "User logged , user_id : ".$userID ;
        }else{
            return "Not logged"; //It is returning this
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了几个类似问题的答案(第一 季度到第二季度),但是没有用。

小智 5

如果使用API​​路由,将没有登录用户。API的身份验证是通过令牌完成的,您可以在Laravel文档中阅读有关它的信息

除非使用Web路由,否则不会调用会话中间件,因此会话不会启动,因此无法使用Auth。

您将API路由与Auth结合使用是不正常的,您想实现的目标是什么?