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

6

10

I've got a database with nullable fields. When I send my values via api resource, laravel is sending null values. I want to get empty strings instead. How can I set it up?

example:

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

I want a json object:

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

instead I've got:

{"active": false, "person": null, "edit": false, "buttons": false, "text": null}
Terrill answered 29/4, 2018 at 16:12 Comment(7)
How about $this->text !== null ? $this->text : '' ? (same for person)Setscrew
@Setscrew inside return?Terrill
Yes. The idea is to return an empty string instead of a null if those values are null. (Keep in mind this will make it impossible to distinguish whether the real value is actually an empty string or a null)Setscrew
@Setscrew oh, this is workingTerrill
@Setscrew you may put an answerTerrill
Here's a shorter version: $this->text ?: ''Acrocarpous
Does this answer your question? If null use other variable in one line in PHPManchukuo
S
10

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.

Setscrew answered 30/4, 2018 at 7:56 Comment(1)
from array_walk to loop´s and array_maps...this is for me the best choice that one can use...i´ve searching a lot for this kind of clean and easy solution...i just wanted to thank you even if it was not my post. regardsEphebe
Z
7

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
        ];
    }
}
Zarger answered 29/4, 2018 at 21:54 Comment(0)
B
2

You can solved with your's database structure ;

$table->string('person')->default('');
Bazluke answered 29/4, 2018 at 16:28 Comment(0)
G
1

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.

Grenade answered 29/4, 2018 at 16:14 Comment(9)
do you mean I should change in my migration: $table->string('person')->nullable(); into: $table->string('person')->default("");?Terrill
yes, but after fresh migration this is giving me an error when I try to put empty value into this column: "message": "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'person' cannot be null (SQL: insert into requirements` (offer_id, active, person, text, updated_at, created_at) values (51, 1, , some text)`Terrill
can you please try $table->string('person')->default('""');?Grenade
I have tried it using $table->string('name')->nullable()->default('""'); & it's saving "" when saving any data to db using tinker.Grenade
it also works if you try $table->string('name')->nullable()->default('');, I have tried it too.Grenade
if a column is nullable, regardless what the default value is, if you provide a NULL it will save a NULL. The default comes into play if you don't provide any value for it.Setscrew
share your migration with us. what is your database? I have tested it using mysqlGrenade
if you send null, then it will save null. In that case, you need to check that value before saving it. something like this 'text' => $this->text == null ? '' :$this->textGrenade
@Grenade I'm sending values (51, 1, , some text) so it is null (from laravel perspective) my json looks like { "id": "51", "active":true, "person": "", "text": "some text here"} , using standard mysql, standard migrations as above, nothing specialTerrill
M
0

You Can Try this solution this will convert every value in nested array null to an empty string

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

Macaroni answered 25/8, 2020 at 12:47 Comment(0)
G
0

You just need to add ( string ) before any nullable field in your resource it convert into empty string 'person' => ( string )$this->person

Goring answered 30/9, 2021 at 12:58 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Neal

© 2022 - 2024 — McMap. All rights reserved.