Laravel API 中当前用户的 ID [英] Current user's ID in Laravel API

查看:21
本文介绍了Laravel API 中当前用户的 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有控制器方法存储并为该方法定义了 api 路由.当我尝试从 $request 存储信息时,一切正常,但当前用户 ID.Auth::user() 返回空值.如何获取该 ID?

I have controller method store and defined api route for that method. When I try to store informations from $request everything is ok but current user ID. Auth::user() return null. How to grab that id?

推荐答案

根据 如何使用 Passport 在 Laravel API 中获取当前用户?

您可以尝试使用此方法访问 api 中间件中的用户 ID:

you can try using this method to access user id in api middleware:

auth('api')->user();

一个例子:

Route::get("me",function (){
    $userInfo=auth('api')->user();
    if ($userInfo!==null)
    {
        return "User is logged in. id:".$userInfo->id;
    }else{
        return "User is not logged in.";
    }
});

对我来说,它在使用不记名令牌进行身份验证时显示了 ID:

for me it has shown the id when it authenticated with a bearer token:

User is logged in. id:6

这篇关于Laravel API 中当前用户的 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆