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

标签 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}

最佳答案

这里还有一个更大的问题,那就是您的字段一开始是否应该为空。通常,您可以通过使字段不为空来解决此问题,这将迫使您在插入/更新时(而不是在显示时)放入一个空字符串。但是,我的确意识到,在数据库中允许空值,但在返回资源时绝不返回空值并非不合理。

话虽如此,您可以通过以下方式解决您的问题:

<?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 ? : '',但需要注意的一点是,对于所有Falset且不一定为null的$this->text ? : ''值,''将返回$this->text。在您的特定情况下,由于text是字符串或null,因此将是相同的,但这并不总是正确的。

关于laravel:如何设置我的资源以提供空字符串而不是null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50088688/

相关文章:

php - Php Elasticsearch 按地理距离排序

php - 验证 Laravel 中的选择表单

php - laravel Eloquent 关系问题

laravel - 字段 [_id] 是元数据字段,不能添加到文档中。使用索引 API 请求参数

php - 如何在 laravel 中异步执行事件

php - Laravel IN 验证或 ENUM 值验证

php - 如何在 Laravel 中将最后一个 ID 插入到数据库中?

php - 可以向excel导入添加多个参数吗?

javascript - 想要在使用 Vue.js 提交之前显示加载文本

php - 找不到 Laravel 5 自定义包类