Search code examples
phpjsonlaravelnulllaravel-5.6

How to convert null values to empty string in Laravel 5.6 json response?


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?


Solution

  • 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