laravel: how to set my resource to give empty string instead of null

if you use php 7 then you should be able to use the double question mark operator:

<?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
        ];
    }
}

You can solved with your's database structure ;

$table->string('person')->default('');

Change your column & Set empty string as default value for that column. Then when you save any column without any value, it will store empty string for it.


There's a greater question that comes into play here and it's whether your field should be nullable to begin with. Normally you could solve this by not having the field to be nullable which will force you to put an empty string in at insert/update time instead of when displaying it. However I do realise that it's not unreasonable to allow nulls in the database but never return them when returning the resource.

This being said you can solve your problem as follows:

<?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 : '', 
        ];
    }
}

As Dvek mentioned this can be shortened to $this->text ? : '' but there's a small caveat that $this->text ? : '' will return '' for all values of $this->text which are falsey and not necessarily null. In your particular case since text is either a string or null it will be the same but this is not always true.

Tags:

Laravel