[英]How to convert null values to empty string in Laravel 5.6 json response?
I have this response from my Laravel 5.6
:我的
Laravel 5.6
有这个回复:
{
"id": 1,
"name": "Test",
"email": "anything@example.com",
"descr": null
}
It comes from this Laravel PHP
code:它来自这个 Laravel
PHP
代码:
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? Laravel 5.6 中是否有任何内置函数可以将空值更改为空字符串? I want to get back this json object:
我想取回这个 json 对象:
{
"id": 1,
"name": "Test",
"email": "anything@example.com",
"descr": ""
}
Any idea?有什么想法吗?
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:使用以下代码在文件夹
app/Http/Middleware
创建一个名为NullToBlank.php
的文件:
<?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)
更改为:
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/Kernel.php
确保添加:
\App\Http\Middleware\NullToBlank::class,
under $middleware
.在
$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卢卡
Add this function before return返回前添加此函数
array_walk_recursive($array,function(&$item){$item=strval($item);}); array_walk_recursive($array,function(&$item){$item=strval($item);});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.