Auth :: id()返回null laravel

时间:2018-08-28 10:38:23

标签: php laravel laravel-5

我有一个功能,其中

public function index(){
   $users = User::doesntHave('roles')->latest()->paginate()->except(Auth::id());
   return UsersResource::collection($users);
}

当我添加Auth::id()时,即使我在控制器上声明了auth Facade,它也会返回null

use Illuminate\Support\Facades\Auth;

这是我的路线,存储在api.php

Route::resource('users','Users\AdminUsersController')->except([
    'create', 'edit'
]);

3 个答案:

答案 0 :(得分:1)

auth:api中间件中添加受auth保护的路由

Route::post('login','LoginController@login');

Route::middleware(['auth:api'])->group(function () {

    Route::resource('users','Users\AdminUsersController')->except([
    'create', 'edit'
    ]);

    //other authenticated Routes goes inside this block

}); 

对于Api身份验证,我建议您使用https://laravel.com/docs/5.6/passport

答案 1 :(得分:0)

您已登录。听起来不像

不要使用Illuminate \ Support \ Facades \ Auth;相反,它只是使用身份验证;。

您可以执行以下操作:

auth()->check(); // this checks to see if you're logged in

$userId = auth()->check() ? auth()->id() : null;

auth()->id(); // this is the same as Auth::id();

auth()->user();

答案 2 :(得分:0)

$ users = User :: doesntHave('roles')-> latest()-> paginate()-> except(Auth :: user()-> id);