问题描述
我只是想在从db获取结果的同时如何将null转换为空字符串。 例如
User::first();
在用户表中,卷号为空值。我希望它转换为空字符串。
解决方法
是的,您可以在引导方法中使用检索到的观察者来执行此操作。
self::retrieved(function ($model) {
$keys = $model->fillable;
foreach ($keys as $key => $value) {
$model->attributes[$value] = @$model->attributes[$value] == null ? '' : $model->attributes[$value];
}
});
,
我有同样的任务,我通过中间件解决了这个问题
创建NullToBlank.php
中间件
<?php
namespace App\Http\Middleware;
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) {
$json = $output->content();
$modelAsArray = json_decode($json,true);
if (is_array($modelAsArray)) {
array_walk_recursive($modelAsArray,function (&$item,$key) {
$item = $item === null ? '' : $item;
});
return response($modelAsArray);
} else {
return $next($request);
}
}
}
}
然后在需要将 NULL
替换为 ""
时应用此中间件