这是我的控制器代码:
public function addEmployer(Request $request)
{
$validator = UserValidations::validateEmployer($request->all());
if ($validator->fails()) {
return response(['status' => false, 'message' => 'Validation Errors', 'errors' => $validator->errors()->all()], 500);
}
try {
$request->request->add(['created_by' => Auth::user()->id]);
$employer = $this->employer->create($request->only($this->employer->getModel()->fillable));
return response(['status' => true, 'message' => 'Employer added', 'data' => $employer], 200);
} catch (Exception $ex) {
return response(['status' => false, 'message' => 'Validation Errors', 'errors' => $ex->getMessage()], 500);
}
}
当我保存时,我得到null
值,并且数据库中有NULL
,因为字段类型是nullable()
,
当我发送空值时我的Json
响应
"first_name": "Adnan12",
"middle_name": null,
"last_name": null,
"street_address": null,
"suit_floor": null,
"city": null,
"state": null,
"zip": null,
"contact_person_first_name": null,
"contact_person_middle_name": null,
"phone_no": null,
"ext": null,
"cell_no": null,
"fax": null,
"email": null,
"comments": null,
"created_by": 9,
"updated_at": "2019-08-30 13:51:17",
"created_at": "2019-08-30 13:51:17",
我想要空字符串而不是NULL
json
响应。如何实现此功能?
在App/Http/Kernel
类中,您可以找到分配给属性$middleware
的IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull
类。
此属性是在每个请求上运行的所有全局中间件的array
。
您可以:
- 删除或注释掉该行,以便每个字符串输入在为空时不会转换为 null。 如果要
- 选择可能是空字符串的字段,请编写自己的中间件,如下所示:
namespace AppHttpMiddleware;
use IlluminateFoundationHttpMiddlewareTransformsRequest as Middleware;
class ConvertEmptyStringsToNull extends Middleware
{
/**
* The names of the attributes that should not be converted to null if empty.
*
* @var array
*/
protected $except = [
'middle_name',
'last_name',
];
protected function transform($key, $value)
{
if (in_array($key, $this->except, true)) {
return $value;
}
return is_string($value) && $value === '' ? null : $value;
}
}
现在,您可以在AppHttpKernel class
的$middleware
属性中将IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class
替换为您自己的AppHttpMiddlewareConvertEmptyStringsToNull::class
。