Search code examples
phplaravelroutesoauthlaravel-passport

How to have a route for both authenticated users and non-authenticated users


I have an issue with auth:api middleware! We have a request that is accessible for both authenticated users and non-authenticated users when I define a route like this for non-authenticated users:

Route::post('{user}/leads', 'UsersController@getContact');

It's ok everything work fine when a guest user requesting this route. is and I can access user with $request->user();

but if pass token with bearer header and get the user with $request->user() of course it doesn't work! because we didn't use auth:api on this route, and if we do we can't access this route with guest users! So I can't find a way that we define one route for both authenticated users that if user is authenticated we get $request->user() and none authenticated users can access that route too!

Thanks in advance.


Solution

  • I found a way to do that I just wrote this:

    $middleware = ['api'];
    if (\Request::header('Authorization')) 
       $middleware = array_merge(['auth:api']);
    Route::group(['prefix' => 'v1', 'namespace' => 'Api', 'middleware' => $middleware], function () {
        //routes here
    });
    

    In api.php route file and it works fine. Thanks