I have this response from my Laravel 5.6
:
{
"id": 1,
"name": "Test",
"email": "anything@example.com",
"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": "anything@example.com",
"descr": ""
}
Any idea?
Advertisement
Answer
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 AppHttpMiddleware;
use IlluminateDatabaseEloquentModel;
use Closure;
class NullToBlank
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $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:
AppHttpMiddlewareNullToBlank::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