i have a registraion api that register user details to database it also genrates token using
laravel passport and saves the token into database
now i am trying to create a get api that will fetch all data from database using token generated
what i have tryed
in
api.php
Route::get('/get_user', [userDEtails::class, 'get_user']);
userDEtails.php controler
public function get_user(Reqest $req)
{
// what code must i add here
}
in post man i want to add token in header as Authorization and api to work
i am using Laravel Framework 9.41.0
3
Answers
Since you’ve said you’re using Laravel Passport for this, try doing this to get the user (and check scopes)
This should ideally work. You will also need to make sure that your route is using the ‘auth:api’ middleware for your route like this –
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 –
OR
instead to get the user object.
To fetch the data from the database using the token generated, you can follow the steps below:
In your get_user function, first retrieve the token from the request header by using the header method on the request object.
Then you can use the TokenRepository provided by Laravel Passport to retrieve the authenticated user associated with the token. You can get an instance of the TokenRepository by using the app helper function:
If the token is valid and an associated user is found, you can then use the User model to fetch the data from the database:
Lastly ,return the fetched data to the client by returning a JSON response
But to take care of any unexpected error ,add some error handling in case the token is invalid or an associated user is not found.
In
Auth::check()
, it will check token is valid or not. Based on that, it will returntrue
orfalse
.In addition, before you send a request to
get_user()
, write thelogin()
method and get the access token. You can use passport or JWTIf you use a Laravel passport can use
bearerToken()
to get the token andAuth::checkToken()
to validate the token.