如何防止Laravel剥离空数组

时间:2018-01-30 12:38:13

标签: laravel

正如标题所说,如何防止Laravel删除输入json中的空数组?示例:给定客户端请求

$.ajax({
    url: "/test",
    data: {
        populatedArray: ["Fine, as long as it has >0 elements"],
        emptyArray: [], // This property will not be available!
        tasks: {
            fooTask: {
                empty: [],
                nullObject: null,
                regular: "It should also work for nested"
            }
        }   
    },
    contentType: "application/json",
});

和控制器

public function test(Request $request) {        
    Log::info(json_encode($request->populatedArray));
    Log::info(json_encode($request->emptyArray));
}

我收到以下日志消息:

[2018-01-30 12:30:01] local.INFO: ["Fine, as long as it has >0 elements"]  
[2018-01-30 12:30:01] local.INFO: null  

我希望第二行产生[]但它不存在于$ request对象中?

2 个答案:

答案 0 :(得分:1)

在将其发送到服务器之前,将数据打包为字符串

$.ajax({
    url: "/stimpack/test/",
    data: { 
        myValue: "all good",
        populatedArray: ["Fine, as long as it has >0 elements"],
        emptyArray: [], // This property will not be available!,
        tasks: JSON.stringify({
            fooTask: {
                empty: [],
                nullObject: null,
                regular: "Hi all"
            }
        }) 
    },
    contentType: "application/json"
});

接下来,在您的控制器中将字符串解压缩到像这样的对象

$inputAsObject = json_decode($request->tasks);

记录它也会显示空数组

Log::info(json_encode($inputAsObject));

另一个好处是你不必担心Laravel将所有东西视为关联数组。这意味着你可以这样做:

Log::info(json_encode($inputAsObject->fooTask->empty));

答案 1 :(得分:0)

将第二个参数作为默认值传递给{{1}}方法

{{1}}