如何在 Laravel 中不使用 trim 获取查询参数或输入
How to get query params or input without trim in Laravel
我正在开发一个使用输入资源列表进行过滤的端点。
比如我输入的是“key”,它可以检索到:
keyboard
KeyBoard
red key
key of pc
但是,如果我的输入是“键”<- 白色 space,我必须使用完整的输入,而不是 trim,结果:
key of pc
所以,端点是在 Laravel 中创建的,但是当我尝试获取查询参数或输入时,我得到了数据 trimmed.
...
public function __invoke(CustomRequest $request)
{
dd($request->query('search')); // prints "key" and not "key "
...
}
而 CustomRequest 是:
class CustomRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(): array
{
return [
'search' => ['sometimes', 'nullable', 'string'],
];
}
}
Laravel 使用 TrimStrings
中间件来 trim 输入。如果您想获得未trimmed 输入,您可以将中间件中的字段名称列入白名单
//app/Http/Middleware/TrimStrings.php
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
// Add the name of field for which input should not be trimmed here
'search'
];
}
我正在开发一个使用输入资源列表进行过滤的端点。
比如我输入的是“key”,它可以检索到:
keyboard
KeyBoard
red key
key of pc
但是,如果我的输入是“键”<- 白色 space,我必须使用完整的输入,而不是 trim,结果:
key of pc
所以,端点是在 Laravel 中创建的,但是当我尝试获取查询参数或输入时,我得到了数据 trimmed.
...
public function __invoke(CustomRequest $request)
{
dd($request->query('search')); // prints "key" and not "key "
...
}
而 CustomRequest 是:
class CustomRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(): array
{
return [
'search' => ['sometimes', 'nullable', 'string'],
];
}
}
Laravel 使用 TrimStrings
中间件来 trim 输入。如果您想获得未trimmed 输入,您可以将中间件中的字段名称列入白名单
//app/Http/Middleware/TrimStrings.php
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
// Add the name of field for which input should not be trimmed here
'search'
];
}