Create a GET API with authorization token using Laravel
P粉239164234
P粉239164234 2023-12-25 09:40:02
0
1
359

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粉239164234
P粉239164234

reply all(1)
P粉475126941

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!