Search code examples
phplaravellaravel-passport

How to get the user id from laravel passport token?


I'm using smartins/passport-multiauth passport, in PostMan I Made a post request sending this data through the request; The idea is when the user submits an order, the token of that user will be passed through the request.. how can I get the user_id of that token so that I can store it in the Orders table?

{

        "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
    }

Solution

  • You almost there... you should pass the id of the user in $token like below:

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

    or

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