laravel:如何设置我的资源以提供空字符串而不是null

时间:2018-04-29 16:12:35

标签: laravel

我有一个可以为空的字段的数据库。当我通过api resource发送我的值时,laravel会发送null个值。我想换空字符串。我该如何设置?

示例:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class RequirementResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'active' => $this->active,
            'person' => $this->person, //sometimes has null value
            'edit' => false,
            'buttons' => false,
            'text' => $this->text, //sometimes has null value
        ];
    }
}

我想要一个json对象:

{"active": false, "person": "", "edit": false, "buttons": false, "text": ""}
相反,我得到了:

{"active": false, "person": null, "edit": false, "buttons": false, "text": null}

5 个答案:

答案 0 :(得分:3)

如果您使用php 7,那么您应该能够使用双问号运算符:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class RequirementResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'active' => $this->active,
            'person' => $this->person ?? '', //sometimes has null value
            'edit' => false,
            'buttons' => false,
            'text' => $this->text ?? '', //sometimes has null value
        ];
    }
}

答案 1 :(得分:2)

这里有一个更大的问题,那就是你的领域是否应该是可以开头的。通常你可以通过不使字段可以为空来解决这个问题,这会强制你在插入/更新时放入一个空字符串而不是显示它。但是我确实意识到在数据库中允许空值但在返回资源时永远不会返回它们并不是不合理的。

据说你可以解决你的问题如下:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class RequirementResource extends Resource
{
    public function toArray($request)
    {
        return [
            'active' => $this->active,
            'person' => $this->person !== null ? $this->person : '',
            'edit' => false,
            'buttons' => false,
            'text' => $this->text !== null ? $this->text : '', 
        ];
    }
}

正如Dvek所说,这可以缩短为$this->text ? : '',但有一点需要注意$this->text ? : ''''返回$this->text所有 falsey <的值{}} / em>并不一定是null。在您的特定情况下,因为text是字符串或null,所以它将是相同的,但并不总是如此。

答案 2 :(得分:1)

更改列和&amp;将空字符串设置为该列的默认值。然后当你保存任何没有任何值的列时,它将为它存储空字符串。

答案 3 :(得分:1)

您可以使用您的数据库结构解决;

b

答案 4 :(得分:0)

您可以尝试此解决方案,它将嵌套数组null中的每个值转换为空字符串

array_walk_recursive($array, function (&$item) { $item = strval($item);});