以下是这一已有9年历史的函数的更新版本:
/**
* Converts a form input request field's type to its proper type after values are received stringified.
*
* Function flow:
* 1. Check if it is an array, if yes, return array
* 2. Remove unused spaces
* 3. Check if it is '0', if yes, return 0
* 4. Check if it is empty, if yes, return blank string
* 5. Check if it is 'null', if yes, return null
* 6. Check if it is 'undefined', if yes, return null
* 7. Check if it is '1', if yes, return 1
* 8. Check if it is numeric
* 9. If numeric, this may be a integer or double, must compare this values
* 10. If string, try parse to bool
* 11. If not, this is string
*
* (c) José Moreira - Microdual (www.microdual.com)
* With the help of Svisstack (http://stackoverflow.com/users/283564/svisstack)
*
* Found at: https://stackoverflow.com/questions/2690654/how-to-get-the-real-type-of-a-value-inside-string
*
* @param string $string
* @return mixed
*/
function typeCorrected($string) {
if (gettype($string) === 'array') {
return (array)$string;
}
$string = trim($string);
if ($string === '0') { // we must check this before empty because zero is empty
return 0;
}
if (empty($string)) {
return '';
}
if ($string === 'null') {
return null;
}
if ($string === 'undefined') {
return null;
}
if ($string === '1') {
return 1;
}
if (!preg_match('/[^0-9.]+/', $string)) {
if(preg_match('/[.]+/', $string)) {
return (double)$string;
}else{
return (int)$string;
}
}
if ($string == 'true') {
return true;
}
if ($string == 'false') {
return false;
}
return (string)$string;
}
FormData.append()
回到正确的PHP类型:
public function handle($request, Closure $next)
{
$input = $request->all();
foreach($input as $key => $value) {
$input[$key] = $this->typeCorrected($value);
}
$request->replace($input);
return $next($request);
}
-
要创建它,请键入CLI
php artisan make:middleware TransformPayloadTypes
-
然后贴在上面
handle
功能。
-
别忘了把它贴在墙上
typeCorrected
private function
在你的中间件类,但我不声称是一个超级专家。
你可以想象
$request->all()
类型已更正
函数执行此操作。我已经在一个应用程序中运行了几个星期了,所以边缘案例可以保留下来,但实际上,它是按预期工作的。
// note: `route()` is from Tightenco Ziggy composer package
const post = await axios.post(route('admin.examples.create', {
...this.example,
category: undefined,
category_id: this.example.category.id,
}));
然后,在你的Laravel控制器中,你可以
\Log::debug($request->all());
看到这样的东西:
[2020-10-12 17:52:43] local.DEBUG: array (
'status' => 1,
'slug' => 'asdf',
'name' => 'asdf',
'category_id' => 2,
)
'status' => 1,
而不是
'status' => '1',
所有这些都允许您通过Axios提交JSON有效负载,并在实际有效负载类型发生变化时在FormRequest类和控制器中接收非嵌套值。我发现其他的解决方案太复杂了。上述解决方案允许您轻松地从纯JavaScript提交平面JSON有效负载(到目前为止,哈哈)。