【问题标题】:Laravel : get user id null tested by postman from Json dataLaravel:从Json数据中获取邮递员测试的用户ID为空
【发布时间】:2020-12-08 06:05:23
【问题描述】:

我正在尝试通过 Laravel 创建一个 API,我制作了表格、模型和控制器,在我的一个控制器中我有这个方法:

public function order(Request $request)
{
    $datas = json_decode($request->getContent(), true);
            
    $insert = Order::create(
        [
            'user_id'=>$request->user_id,
//            'user_id'=>$datas->user_id,
            'status'=>'ordered',
        ]);
}

我通过邮递员在正文面板中发送这样的原始数据列表对其进行了测试:-

[
    {
        "user_id": 1,
        "details": [
            {
                "product_id": 1,
                "quantity": 4
            },
            {
                "product_id": 2,
                "quantity": 3
            }
        ]
    }
]

当我测试它时,我得到了错误'user_id' cannot be null;当我使用上面的注释行时,我得到Trying to get property 'user_id' of non-object in file

【问题讨论】:

  • 使用dd($request)后的输出是什么?
  • @ThânLƯƠNG 我现在将添加请求和数据 dd
  • @ThânLƯƠNG 我添加了你问的内容
  • 你传入对象数组的格式意味着如果你这样做$datas[0]['user_id']你应该得到你的用户ID

标签: php json laravel postman


【解决方案1】:

您正在发送一个数组,然后对其进行解码,因此您需要指明要使用哪个数组元素。此外,将true 作为第二个参数传递给json_decode 会返回一个数组而不是对象。所以这样的事情应该可以工作:

public function order(Request $request)
{
    $datas = json_decode($request->getContent(), true);
        
    $insert = Order::create([
        'user_id' => $datas[0]['user_id'],
        'status'=>'ordered',
    ]);
}

【讨论】:

    【解决方案2】:

    Estas enviando un objeto dentro de una arreglo, envia el objeto sin estar dentro del arreglo es decir:

    {
         "user_id": 1,
            "details": [
                {
                    "product_id": 1,
                    "quantity": 4
                },
                {
                    "product_id": 2,
                    "quantity": 3
                }
            ]
        }
    

    【讨论】:

      猜你喜欢
      • 2018-01-01
      • 1970-01-01
      • 2018-11-23
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 2020-07-07
      相关资源
      最近更新 更多