I'm working on an endpoint that filters with input a list of resources.
For example, if my input is "key", it can retrieve:
keyboard
KeyBoard
red key
key of pc
but, if my input is "key " <- with white space, I have to use complete input, and not trim, and the result:
key of pc
So, the endpoint was made in Laravel, but when I try to get the query param or input, I get the data trimmed.
...
public function __invoke(CustomRequest $request)
{
dd($request->query('search')); // prints "key" and not "key "
...
}
And CustomRequest is:
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'],
];
}
}
CodePudding user response:
Laravel uses TrimStrings
middleware to trim the inputs. If you want to get untrimmed input you can whitelist the field name in the middleware
//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'
];
}