4

I have this response from my Laravel 5.6:

{
    "id": 1,
    "name": "Test",
    "email": "[email protected]",
    "descr": null
}

It comes from this Laravel PHP code:

public function show($id) {
    return Client::find($id);
}

Is there any built-in function in Laravel 5.6 to change the null value to empty sting? I want to get back this json object:

{
    "id": 1,
    "name": "Test",
    "email": "[email protected]",
    "descr": ""
}

Any idea?

5
  • Any specific reason you want empty value rather than null? Commented Apr 1, 2018 at 17:05
  • Because I get null on the frontend there I need to write an "if" statement to handle nulls. I work with many text filed (in SQL) witch can be null in database, but I'm too lazy to handle nulls on 50+ locations in my code... It could be simplier if these fields are not null. Commented Apr 1, 2018 at 17:09
  • how is your need to handle null any different from an empty string? Not being awkward just maybe you don't need empty string? Also, It's better to refactor to handle data correctly at the right point, rather than change something further up the chain that might might be unexpected later on Commented Apr 1, 2018 at 17:12
  • good point, but I'm qurious to the answer :) Commented Apr 1, 2018 at 17:26
  • 2
    Yeah fair enough. null means nothing, does not exist, whereas an empty string for a description means there is a description (it's set etc), it's just empty. Commented Apr 1, 2018 at 17:29

2 Answers 2

5

If you don't have any choice and you really need it, you can do this using a middleware.

Create a file named NullToBlank.php in the folder app/Http/Middleware with the following code:

<?php

namespace App\Http\Middleware;

use Illuminate\Database\Eloquent\Model;
use Closure;

class NullToBlank
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $output = $next($request);
        if($output instanceof Model)
            return response()->json(array_map(function ($value) {
                return $value === null ? '' : $value;
            }, $output->toArray()));

        return $output;
    }
}

This is the case when you need to change values only on the returned model, not on related models. In the case of returned + all the related models, then the condition if($output instanceof Model) changes to:

if($output instanceof Model) {
    $modelAsArray = $output->toArray();

    array_walk_recursive($modelAsArray, function (&$item, $key) {
        $item = $item === null ? '' : $item;
    });

    return response()->json($modelAsArray);
}

In your app/Http/Kernel.php make sure you add:

\App\Http\Middleware\NullToBlank::class,

under $middleware.

This should do the trick. I haven't tested it personally, I just did on the go, if you have problems, let me know.

Luca

Sign up to request clarification or add additional context in comments.

4 Comments

This doesn't answer the question. And how is all of this code any better than just simply checking is_null()? Or even just if (is_null($desc)) {$desc = '';}
@James well, it actually does. He is trying to return as a response a Model, that automatically turns into a JSON response with the attributes of the returned Model. He said he doesn't want to make the check if it's null to convert it to an empty string everytime he needs it. I suppose he is trying to get this response via an AJAX request, therefore printing the value of null in JavaScript will print the string 'null', instead of an empty string. This code just checks if the response is a model, in that case changes null to empty string and returns it as a json response.
"Is there any built-in function in Laravel 5.6 to change the null value to empty sting?" I think they specifically want to use return Client::find($id); in some way that will return empty string rather than null. Rather than a full blown new class that needs instantiating somewhere and plumbing in to their current code. It is a viable alternative, and why I never dvoted, but it doesn't answer the question - that would be "yes like this" or "no you can't" (essentially) :)
@James in this case you are totally right! Mine can be considered as a viable alternative indeed. Even though there might be several alternatives. It depends on the needs.
0

Add this function before return

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

1 Comment

Please make sure you markup your code and provide valid code snippets. This is a half snippet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.