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
nullmeans nothing, does not exist, whereas an empty string for a description means there is a description (it's set etc), it's just empty.