如何清理laravel 5.X请求输入? [英] How can I sanitize laravel 5.X Request inputs?
问题描述
我有MyRequest.php
类扩展了App\Http\Requests\Request
.我想trim()
验证之前的每个输入,因为在其后面带有空格的电子邮件不会通过验证.
I have MyRequest.php
class extending App\Http\Requests\Request
. I want to trim()
every input before validation because an e-mail with a space after it does not pass validation.
但是sanitize()
已从src/Illuminate/Foundation/Http/FormRequest.php
推荐答案
我刚遇到相同的问题.
我想向您展示另一种不使用extends
但使用traits
的方法. (我将从Tarek Adam获得示例类).
I just came across for the same problem.
I'd like to show you another way of doing it without extends
but with traits
. ( I will take the Example Classes from Tarek Adam ).
PHP 特质类似于将被注入到二手课.一个主要的区别是,Trait不需要像extends那样的任何依赖项.这意味着您可以将一个特征用于多个类,而不仅仅是一个类.适用于控制器,请求和任何您喜欢的东西.
PHP Traits are like functions which will be injected into the used class. The one main difference is that a Trait doesn't need any dependency like a extends do. This means you can use a trait for more then just one class e.x. for Controllers, Requests and whatever you like.
Laravel在BaseController中提供了一些特征,我们可以做同样的事情.
Laravel provides some traits in the BaseController, we can do the same.
在\App\Traits\SanitizedRequest.php
中的文件中创建一个特征.您可以在无关紧要的任何地方创建它.您必须确保提供正确的名称空间.
Create a trait as file in \App\Traits\SanitizedRequest.php
. You can create it anywhere it doesn't matter really. You have to provide the correct namespace for sure.
namespace App\Trait;
trait SanitizedRequest{
private $clean = false;
public function all(){
return $this->sanitize(parent::all());
}
protected function sanitize(Array $inputs){
if($this->clean){ return $inputs; }
foreach($inputs as $i => $item){
$inputs[$i] = trim($item);
}
$this->replace($inputs);
$this->clean = true;
return $inputs;
}
}
在您的请求中,可以将特征与use SanitizedRequest
关键字一起使用.
In your Request you can use the trait with use SanitizedRequest
keyword.
namespace App\Http\Requests\Forms;
use App\Http\Requests\Request;
use App\Trait\SanitizedRequest; // Import the Trait
class ContactRequest extends Request {
use SanitizedRequest; // This line adds all the Trait functions to your current class
public function authorize(){ return true; }
public function rules(){ return []; }
}
这篇关于如何清理laravel 5.X请求输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!