我是 laravel 5.8 的新手,我无法在 api Controller 中使用 Auth
,以下是详细信息:
- 我已将默认用户表从
users
更改为User
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',
];
}
没有改变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, ], ], ];
我的问题:如何让 Auth::check() 在此 Controller 中工作并获取用户 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
}
}
}
最佳答案
如果使用 API 路由,则不会有登录用户。 API 的身份验证是通过 token 完成的,您可以在 Laravel docs 中阅读相关信息.
除非您使用网络路由,否则不会调用 session 中间件,因此 session 不会启动,因此无法使用 Auth。
您尝试实现什么,因为将 Auth 与 API 路由一起使用是不正常的。
关于php - 无法在 Controller 中获取用户 ID 并且 Auth::check() 不工作 - Laravel 5.8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55591896/