如何从laravel护照令牌获取用户ID?

时间:2019-12-16 07:29:04

标签: php laravel laravel-passport

我使用的是smartins / passport-multiauth护照,在PostMan中,我发出了发布请求,并通过请求发送了该数据; 想法是,当用户提交订单时,该用户的令牌将通过请求传递。.如何获取该令牌的user_id,以便将其存储在Orders表中?

{

        "place_id": 2,
        "token": "b715d124c04125acae2dda144021724b3266a361785f29883105c138d23ecdb0da1fd48de719039a",
        "items": [
            {
                "id": 4,
                "quantity": 5
            },
            {
                "id": 5,
                "quantity": 3
            }
        ]

}
public function new_order(Request $request)
    {
        $token= auth('api')->user();
        $order = Order::create([
            'place_id'=>$request->place_id,
            'code_id'=>$request->code_id,
            'user_id'=>$token
        ]);

        $items = $request->input('items', []);
        foreach ($items as $item)
        {
            ItemOrder::create([
                'order_id'=>$order->id,
               'item_id'=>$item['id'] ,
               'quantity'=>$item['quantity'] ,
            ]);
        }

        return response()->json([
            'status' => (bool)$order,
            'order' => $order,
            'message' => $order ? 'Your order has been sent !' : 'There is some error!'
        ]);
        //ToDo:notificaion to restaurant
    }

3 个答案:

答案 0 :(得分:2)

您快到了……您应该在$token中传递用户ID,如下所示:

$token = auth('api')->user()->id 

'user_id' = auth('api')->user()->id;

答案 1 :(得分:1)

只需获取经过身份验证的用户ID,即可:

'user_id' = auth('api')->user()->id;

答案 2 :(得分:0)

尝试以下操作:-

return response()->json([
   'status' => (bool)$order,
   'user_id'=> \Auth::user()->id,
   'order' => $order,
   'message' => $order ? 'Your order has been sent !' : 'There is some error!'
]);