Laravel 5.6 - How to get auth()->user() or $response->user() in api controller?

前端 未结 2 527
我在风中等你
我在风中等你 2020-12-16 21:24

In api.php routes file below, there are public routes and private routes:

Route::group([\'namespace\' => \'API\'], function() {

     // Publ         


        
相关标签:
2条回答
  • 2020-12-16 21:43

    Pass the api guard as a parameter to fetch the authorized user without the middleware protecting the request.

    $request->user('api');
    
    // Or
    
    auth('api')->user();
    
    0 讨论(0)
  • 2020-12-16 21:51

    You are referencing Request from a root namespace: \Request. Instead, you should reference the Illuminate\Http\Request class.

    You should remove the \ from your parameter and add the following line to your imports.

    use Illuminate\Http\Request;

    Alternatively, you could also reference the request class directly in your method:

    class TestController extends Controller {
    
        public function testauth1(Illuminate\Http\Request $request) {
            return $request->user();
        }
    
        public function testauth2() {
            return auth()->user(); // returns user
        }
    
    }
    

    The auth() helper method or Auth Facade is globally available. It doesn't depend on the request that you are trying to access. The same goes for the request() and Request:: helpers I believe. In the case you are giving, you are referencing a wrong Request instance, hence giving a unexpected result.

    0 讨论(0)
提交回复
热议问题