刚才开始知道Laravel 5.4有一个很棒的功能 TrimString ,可以从任何输入中删除空格。我想在5.3项目中使用这个中间件,不知道怎么做?
我刚刚从Laravel的GitHub回购中复制了中间件,但它没有用。
由于
答案 0 :(得分:2)
如果您想在Laravel 5.3
中使用此功能。
将这两个类添加到App\Http\Middleware
https://github.com/laravel/laravel/blob/master/app/Http/Middleware/TrimStrings.php
将namespace
更新为App\Http\middleware
。
像:
<强> TransformsRequest.php 强>
namespace App\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\ParameterBag;
class TransformsRequest
{
/**
* The additional attributes passed to the middleware.
*
* @var array
*/
protected $attributes = [];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, ...$attributes)
{
$this->attributes = $attributes;
$this->clean($request);
return $next($request);
}
/**
* Clean the request's data.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function clean($request)
{
$this->cleanParameterBag($request->query);
$this->cleanParameterBag($request->request);
if ($request->isJson()) {
$this->cleanParameterBag($request->json());
}
}
/**
* Clean the data in the parameter bag.
*
* @param \Symfony\Component\HttpFoundation\ParameterBag $bag
* @return void
*/
protected function cleanParameterBag(ParameterBag $bag)
{
$bag->replace($this->cleanArray($bag->all()));
}
/**
* Clean the data in the given array.
*
* @param array $data
* @return array
*/
protected function cleanArray(array $data)
{
return collect($data)->map(function ($value, $key) {
return $this->cleanValue($key, $value);
})->all();
}
/**
* Clean the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function cleanValue($key, $value)
{
if (is_array($value)) {
return $this->cleanArray($value);
}
return $this->transform($key, $value);
}
/**
* Transform the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function transform($key, $value)
{
return $value;
}
}
<强> TrimStrings.php 强>
namespace App\Http\Middleware;
class TrimStrings extends TransformsRequest
{
/**
* The attributes that should not be trimmed.
*
* @var array
*/
protected $except = [
//
];
/**
* Transform the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function transform($key, $value)
{
if (in_array($key, $this->except)) {
return $value;
}
return is_string($value) ? trim($value) : $value;
}
}
并添加到您的App\Http\Kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\TransformsRequest::class,
\App\Http\Middleware\TrimStrings::class,
];
使用它只需使用:
dd(request('email'));
更多信息: