Home  >  Q&A  >  body text

Create a GET API with authorization token using Laravel

I have a Registration API which registers user details to the database and it also generates tokens using laravel Passport and save the token to the database

Now I'm trying to create a get api which will get all the data from the database using the generated token

What I tried

exist api.php

Routing::get('/get_user', [userDEtails::class, 'get_user']);

userDEtails.php Controller

public function get_user(Reqest $req)
{

// what code must i add here
    
}

In postman I want to add token in header as authorization and api to work

I am using Laravel framework 9.41.0

P粉239164234P粉239164234322 days ago461

reply all(1)I'll reply

  • P粉475126941

    P粉4751269412023-12-26 00:53:25

    Since you have said you are using Laravel Passport for this, try executing this to get the user (and check the scope)

    public function get_user(Request $request)
    {
        $user = $request->user();
    }

    Ideally this should work. You also need to make sure your route uses the 'auth:api' middleware like this route -

    Route::get('/get_user', [userDEtails::class, 'get_user'])->middleware('auth:api');

    If for some reason you can't use the "auth:api" middleware for this route and need to stick with "web" or something else, you can use -

    $user = auth()->guard('api')->user()

    or

    $user = $request->user('api')

    Instead of getting the user object.

    reply
    0
  • Cancelreply