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

gil*_*usz 8 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
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要一个 json 对象:

{"active": false, "person": "", "edit": false, "buttons": false, "text": ""}
Run Code Online (Sandbox Code Playgroud)

相反,我有:

{"active": false, "person": null, "edit": false, "buttons": false, "text": null}
Run Code Online (Sandbox Code Playgroud)

apo*_*fos 9

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

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

<?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 : '', 
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

作为Dvek提到这可以缩短到$this->text ? : '',但有一小告诫说,$this->text ? : ''将返回''的所有值$this->text它们falsey并不见得空。在您的特定情况下,由于 text 是字符串或 null 它将是相同的,但这并不总是正确的。


小智 6

如果您使用 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
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)