Get user by token - sanctum Hi there,
I have a token like 1|bTNlKViqCkCsOJOXWbtNASDKF7SyHwzHOPLNH and I wanna find the user by this token.
note: I can not use auth()->user in a specific controller. thanks in advance
@iamamirsalehi If you check Sanctum's source code you can see that SHA256 is used to hash the tokens inside the database and how Sanctum fetches a token from the database. You could also just use where and query for the hashed token directly.
https://github.com/laravel/sanctum/blob/2.x/src/PersonalAccessToken.php (See findToken)
$token = PersonalAccessToken::where('token', $hashedToken)->first();
After fetching the token you can simply use $token->tokenable to get the user the token belongs to.
$user = $token->tokenable;
Other option in Laravel 8 can be
use Laravel\Sanctum\PersonalAccessToken;
$token = PersonalAccessToken::findToken($hashedTooken);
now we can get the user data
$user = $token->tokenable;
You can just use
$user = auth('sanctum')->user()
@ryan_ thanks !
its work for me
@ryan_ Exactly what I needed today, thank you.
@ryan_ I used your approach and got what I needed , thanks
@ryan_ Thanks , that worked for me.
even easier still, as long as your route has passed through the sanctum middleware you can just use,
$user = $request->user();
Please sign in or create an account to participate in this conversation.