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

Wonka picture Wonka · Jun 6, 2018 · Viewed 22.4k times · Source

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

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

     // Public routes (auth not required)
     Route::group([], function() {
         Route::get('/testauth1', 'TestController@testauth1');
         // more public routes...
     });

     // Private routes (auth required)
     Route::group(['middleware' => 'auth:api'], function() {
         Route::get('/testauth2', 'TestController@testauth2');
         // more private routes...
     });

});

In the TestContoller these are the 2 methods called above:

class TestController extends Controller {

    public function testauth1(\Request $request) {
      // return auth()->user(); // does not return user
      return $request->user(); // does not return user
    }

    public function testauth2() {
      return auth()->user(); // returns user
    }

}

Since the private route group has the auth:api middleware, we will ensure the user is authenticated by checking the token supplied in the Authorization Bearer header. Only if a valid token is present will the private routes be rendered to the authenticated user. This is why TestController@testauth2 returns the auth user correctly.

Now, anyone can access the public routes, with or without token. If there is no token supplied in the Authorization Bearer header, then we'll have no authenticated user, which makes sense. This is why TestController@testauth1 does not return an auth user. However, when a logged in user accesses /testauth1 public route, they provide their token in the Authorization Bearer header and therefore should be returned in TestController@testauth1 if not with auth()->user() at least with the $request->user() but we can't seem to access the user with their supplied token in that method.

Any idea how we can access the valid token user in all public route methods?

Answer

Aken Roberts picture Aken Roberts · Jun 6, 2018

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();