laravel - 如何防止 Laravel 剥离空数组

标签 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",
});

和 Controller
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 对象中??

最佳答案

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

$.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"
});

接下来,在您的 Controller 中,将字符串解压为对象,如下所示
$inputAsObject = json_decode($request->tasks);

记录它也会显示空数组
Log::info(json_encode($inputAsObject));

另一个好处是您不必担心 Laravel 将所有内容都视为关联数组。这意味着你可以这样做:
Log::info(json_encode($inputAsObject->fooTask->empty));

关于laravel - 如何防止 Laravel 剥离空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48521694/

相关文章:

laravel - 如何使用 Laravel 翻译字符串?这没用

php - Laravel 在学校活跃时对用户进行身份验证

php - 如何在 laravel 5.2 中检索行中的常用单词

laravel - Created_at 保存时区错误

php - laravel 侦察兵 : How to update index in controller

php - Laravel 表删除 id 列

php - 登录 laravel 后的 Flash 消息

php - 如何从数组输出中删除垃圾数据

php - 拉维尔 : Undefined index: driver

php - 在 ubuntu 中安装 laravel 时出现错误