laravel数据验证_Laravel中的数据验证:正确的方法

laravel数据验证

If an app was a world then data would be its currency. Every app, no matter what its purpose, deals in data. And almost every type of app works with user input, which means it expects some data from users and acts on it accordingly. But that data needs to be validated to make sure it is of correct type and a user (with nefarious intent) is not trying to break or crack into your app. Which, if you are making an application which requires user input, is why you would need to write code to validate that data as well before you do anything with it.

如果应用是一个世界,那么数据将是其货币。 每个应用程序,无论其目的是什么,都将处理数据。 几乎每种类型的应用程序都可以与用户输入配合使用,这意味着它需要用户的一些数据并据此进行操作。 但是,该数据需要进行验证以确保其类型正确,并且用户(出于恶意目的)没有试图破坏或破解您的应用程序。 如果要制作需要用户输入的应用程序,这就是为什么在执行任何操作之前还需要编写代码来验证数据的原因。

很久以前 (Once Upon a Time)

At some point in time, you probably did your data validation like this:

在某个时间点,您可能会像这样进行数据验证:

<?php
$errors = array();

if ( empty( $_POST['name'] ) || ! is_string( $_POST['name'] ) ) {
    $errors[] = 'Name is required';
} elseif ( ! preg_match( "/^[A-Za-z\s-_]+$/", $_POST['name'] ) ) {
    $errors[] = 'Name can have only alphabets, spaces and dashes';
}

if ( empty( $_POST['email'] ) || ! is_string( $_POST['email'] ) ) {
    $errors[] = 'Email is required';
}

//...........
//.... some more code here
//...........

//display errors
if ( ! empty( $errors ) ) {
    for ( $i = 0; $i < count( $errors ); $i++ ) {
        echo '<div class="error">' . $errors[ $i ] . '</div>';
    }
}

Well, that was the stone age for you. Luckily, we have much better and more sophisticated validation packages these days (and have had them for quite some time in PHP).

好吧,那是您的石器时代。 幸运的是,这些天我们有了更好,更复杂的验证程序包(并在PHP中使用了很长时间)。

If you use any application framework as the foundation of your app, chances are it will have its own or a recommended 3rd party data validation package, especially if it is a full stack framework. Since Laravel is a full stack framework, it comes with its own validation package. As always, you’re not constrained to use that and can use any other data validation package that you want. However, for the purpose of this tutorial, we will stick with what comes with Laravel by default.

如果您使用任何应用程序框架作为应用程序的基础,则该应用程序将有其自己的或推荐的第三方数据验证程序包,尤其是当它是完整堆栈框架时。 由于Laravel是一个完整的堆栈框架,因此它带有自己的验证包。 与往常一样,您不受限制地使用它,并且可以使用所需的任何其他数据验证包。 但是,出于本教程的目的,我们将默认使用Laravel附带的内容。

数据验证:Laravel方法 (Data Validation: The Laravel Way)

The source code for this tutorial is available here. You just need to run composer install to install the Laravel framework inside the project directory before you are able to run this code.

本教程的源代码在此处 您只需要运行composer install即可在项目目录中安装Laravel框架,然后才能运行此代码。

Now continuing the previous example, let’s assume we have a form which has a Name and an Email field and we would like to validate that data before saving it. Here’s how the previous rudimentary attempt at validation would translate with Laravel.

现在继续前面的示例,假设我们有一个包含“名称”和“电子邮件”字段的表单,并且我们想在保存之前验证该数据。 这是Laravel先前验证的初步尝试。

<?php
$validation = Validator::make(
    array(
        'name' => Input::get( 'name' ),
        'email' => Input::get( 'email' ),
    ),
    array(
        'name' => array( 'required', 'alpha_dash' ),
        'email' => array( 'required', 'email' ),
    )
);

if ( $validation->fails() ) {
    $errors = $validation->messages();
}

//...........
//.... some more code here
//...........

//display errors
if ( ! empty( $errors ) ) {
    foreach ( $errors->all() as $error ) {
        echo '<div class="error">' . $error . '</div>';
    }
}

In the code above we Laravel-ified the data validation by making use of the Validator facade. We passed an array of the data that we want to validate and an array of validation rules according to which we want the data validated. We get an object returned to us and then we check if our data validation failed or not. If it failed then we grab the error messages object (an object of Laravel’s MessageBag class) and then looped over it to print out all the error messages. The validation rules we used are built into the validation package and there are many available, some would even check into the database.

在上面的代码中,我们通过使用Validator Facade对Laravel进行了数据验证。 我们传递了要验证的数据数组和要根据其验证数据的验证规则数组。 我们得到一个对象返回给我们,然后我们检查数据验证是否失败。 如果失败,则获取错误消息对象(Laravel的MessageBag类的对象),然后遍历它以打印出所有错误消息。 我们使用的验证规则内置在验证包中,并且有很多可用的规则 ,有些甚至可以检入数据库。

Now, it is not uncommon to come across code where the data validation has been placed at odd places, like in Controller methods or in data Models. Data validation code does not belong in either of those places, as such placement defies the concepts of Single Responsibility and DRY (Don’t Repeat Yourself).

现在,遇到在控制器方法或数据模型中将数据验证放在奇数位置的代码并不少见。 数据验证代码不属于这两个位置,因为这样的位置违反了“ 单一责任”和“ DRY” (请勿重复自己)的概念。

Single Responsibility: One class should have one and only one job to perform. A Controller’s job is to act as a glue between the business logic and the client. It should grab the request and pass it on to someone who can process the request, it should not start processing the request itself.

单一责任:一个班级应该只有一份工作要做。 控制器的工作是充当业务逻辑和客户端之间的粘合剂。 它应该获取请求并将其传递给可以处理请求的人,而不应该开始处理请求本身。

Similarly, a Model’s job is to act as a broker between data source and rest of the application. It should only accept data for saving and give it when asked.

同样,模型的工作是充当数据源与应用程序其余部分之间的中介。 它只应接受要保存的数据并在询问时提供。

There is more than one school of thought on this; some would add data validation to Models but even those would not put actual data validation code inside a Model class. It would most likely be outsourced to another class which would accept data and tell whether the data is valid or not.

关于这一点,有不止一个学派。 有些会向模型添加数据验证,但即使是那些也不会将实际的数据验证代码放入Model类中。 它很可能会外包给另一个类,该类将接受数据并判断数据是否有效。

So where do we put the code which does data validation and which can be used anywhere in the application?

那么,我们将用于数据验证并且可以在应用程序中任何地方使用的代码放在哪里?

验证即服务 (Validation as a Service)

The ideal choice is to move out the validation code into separate class(es) which can be used as needed.

理想的选择是将验证代码移到可以根据需要使用的单独的类中。

Continuing with our previous code example, let’s move it into its own class. Create a directory named RocketCandy inside app directory. This is our main directory (or domain directory) in which we will put all our custom stuff (services, exceptions, utility libraries, etc). Now create Services/Validation directory structure inside RocketCandy. Inside Validation directory, create Validator.php.

继续前面的代码示例,让我们将其移入自己的类。 在app目录中创建一个名为RocketCandy目录。 这是我们的主目录(或域目录),我们将在其中放置所有自定义内容(服务,异常,实用程序库等)。 现在在RocketCandy内创建Services/Validation目录结构。 在Validation目录中,创建Validator.php

Now before we can proceed further, open up your composer.json and after the classmap in autoload node add RocketCandy namespace for PSR-4 autoloading. It would look something like this:

现在,在继续下一步之前,打开您的composer.json并在autoload节点中的类classmap之后添加用于PSR-4自动加载的RocketCandy命名空间。 它看起来像这样:

"autoload": {
		"classmap": [
			"app/commands",
			"app/controllers",
			"app/models",
			"app/database/migrations",
			"app/database/seeds",
			"app/tests/TestCase.php"
		],
		"psr-4": {
			"RocketCandy\\": "app/RocketCandy"
		}
	},

Then in your terminal, run composer dump-autoload -o so that composer can generate the autoloader for our RocketCandy namespace.

然后在您的终端中,运行composer dump-autoload -o以便composer可以为我们的RocketCandy名称空间生成自动加载器。

Now open up RocketCandy/Services/Validation/Validator.php. After we move the validation code from above, it will look something like this:

现在打开RocketCandy/Services/Validation/Validator.php 。 从上方移动验证代码后,它将类似于以下内容:

<?php

namespace RocketCandy\Services\Validation;

class Validator {

    public function validate() {
        $validation = \Validator::make(
            array(
                'name' => \Input::get( 'name' ),
                'email' => \Input::get( 'email' ),
           ),
            array(
                'name' => array( 'required', 'alpha_dash' ),
                'email' => array( 'required', 'email' ),
            )
        );

        if ( $validation->fails() ) {
            return $validation->messages();
        }
        
        return true;
    }

}   //end of class

//EOF

Now we could use this as:

现在我们可以将其用作:

<?php

$validator = new \RocketCandy\Services\Validation\Validator;
$validation = $validator->validate();

if ( $validation !== true ) {
    //show errors
}

This is somewhat better than what we were doing earlier but it is still not ideal for the following reasons:

这比我们之前所做的要好一些,但是由于以下原因,它仍然不理想:

  1. Our Validation class still is not DRY enough. We would need to copy over all this validation code to another class to validate data of another entity.

    我们的Validation类仍然不够干。 我们需要将所有这些验证代码复制到另一个类中,以验证另一个实体的数据。
  2. Why are we fetching input data inside the validation class? There is no reason to do it there because it would limit us as to which data we can validate. Here we would be able to validate this data only if it came from a form input.

    为什么我们在验证类中获取输入数据? 没有理由在那里做,因为这会限制我们可以验证哪些数据。 在这里,仅当数据来自表单输入时,我们才能验证该数据。
  3. There is no way of overriding validation rules, they are set in stone.

    没有任何方法可以覆盖验证规则,它们是一成不变的。
  4. The mechanism by which we get to know whether the data validated or not is not clean. Sure, it serves the purpose but this can definitely be improved upon.

    我们了解数据是否经过验证的机制并不干净。 当然,它可以达到目的,但是绝对可以改进。
  5. We are using a pseudo static call to Laravel’s validation package. This can be improved upon as well.

    我们正在使用对Laravel验证包的伪静态调用。 这也可以改进。
解? (Solution?)

We abstract out the validation code a bit further and we make use of exceptions.

我们将验证代码进一步抽象出来,并利用异常。

First, let’s make our own custom exceptions. Create the Exceptions directory under RocketCandy and create BaseException.php. Open it up and put the following code in it.

首先,让我们创建自己的自定义异常。 在RocketCandy下创建Exceptions目录,并创建BaseException.php 。 打开它,并在其中添加以下代码。

<?php

namespace RocketCandy\Exceptions;

use Exception;
use Illuminate\Support\MessageBag;

abstract class BaseException extends Exception {

	protected $_errors;

	public function __construct( $errors = null, $message = null, $code = 0, Exception $previous = null ) {
		$this->_set_errors( $errors );

		parent::__construct( $message, $code, $previous );
	}

	protected function _set_errors( $errors ) {
		if ( is_string( $errors ) ) {
			$errors = array(
				'error' => $errors,
			);
		}

		if ( is_array( $errors ) ) {
			$errors = new MessageBag( $errors );
		}

		$this->_errors = $errors;
	}

	public function get_errors() {
		return $this->_errors;
	}

}	//end of class


//EOF

Here we created an abstract class and all our custom exceptions would inherit this class. The first parameter for the constructor is what we are concerned with, so let’s look at that. We make use of Laravel’s MessageBag to store our errors (if they are not in it already) so that we would have a uniform way to loop through and display those errors irrespective of whether the exception was thrown by validation service or any other. The _set_errors() method thus checks if a single error message as a string was passed or an array of error messages was passed. Accordingly, it stores them in a MessageBag object (unless it is already inside in which case it would be stored as is). And we have a getter method get_errors() which just returns the contents of our class variable as is.

在这里,我们创建了一个抽象类,所有自定义异常都将继承该类。 构造函数的第一个参数是我们所关心的,让我们来看一下。 我们利用Laravel的MessageBag来存储错误(如果它们尚不在其中),这样我们就可以采用统一的方式遍历并显示这些错误,而与验证服务或其他任何异常是否引发异常无关。 _set_errors()方法因此检查是否传递了单个错误消息作为字符串,或者是否传递了错误消息数组。 因此,它将它们存储在MessageBag对象中(除非它已经在内部,在这种情况下它将按原样存储)。 我们有一个getter方法get_errors()get_errors()按原样返回类变量的内容。

Now, in the same directory create ValidationException.php and its code will be:

现在,在同一目录中创建ValidationException.php ,其代码将为:

<?php

namespace RocketCandy\Exceptions;

class ValidationException extends BaseException {
}	//end of class


//EOF

That’s it, we don’t need anything else in here, it will be an empty shell because all that we need done will be handled by BaseException.

就是这样,我们在这里不需要其他任何东西,它将是一个空shell,因为我们需要做的所有事情都将由BaseException处理。

Now, we proceed with re-tooling our Validator class. We need to abstract out the validation code, throw ValidationException on error(s) and allow overriding of validation rules. So it would look like this:

现在,我们继续重新构建Validator类。 我们需要抽象出验证代码,对错误抛出ValidationException并允许覆盖验证规则。 所以它看起来像这样:

<?php

namespace RocketCandy\Services\Validation;

use Illuminate\Validation\Factory as IlluminateValidator;
use RocketCandy\Exceptions\ValidationException;

/**
 * Base Validation class. All entity specific validation classes inherit
 * this class and can override any function for respective specific needs
 */
abstract class Validator {

	/**
	 * @var Illuminate\Validation\Factory
	 */
	protected $_validator;

	public function __construct( IlluminateValidator $validator ) {
		$this->_validator = $validator;
	}

	public function validate( array $data, array $rules = array(), array $custom_errors = array() ) {
		if ( empty( $rules ) && ! empty( $this->rules ) && is_array( $this->rules ) ) {
			//no rules passed to function, use the default rules defined in sub-class
			$rules = $this->rules;
		}

		//use Laravel's Validator and validate the data
		$validation = $this->_validator->make( $data, $rules, $custom_errors );

		if ( $validation->fails() ) {
			//validation failed, throw an exception
			throw new ValidationException( $validation->messages() );
		}

		//all good and shiny
		return true;
	}

} //end of class

//EOF

Here in this abstract class we have:

在这个抽象类中,我们有:

  1. Abstracted out the validation code. It can be used as is for validating data of any entity.

    抽象出验证码。 它可以原样用于验证任何实体的数据。
  2. Removed data fetching from the class. Validation class does not need to know where the data is coming from. It accepts an array of data to validate as a parameter.

    从类中删除了数据获取。 验证类不需要知道数据来自何处。 它接受数据数组作为参数进行验证。
  3. Removed validation rules from this class. Each entity can have its own set of validation rules either defined in the class or they can be passed as array to validate(). If you want to define rules in the child classes and want to be sure they’re present, I wrote about emulating abstract properties in PHP sometime back.

    从此类中删除了验证规则。 每个实体可以在类中定义自己的一组验证规则,也可以将它们作为数组传递给validate()如果您想在子类中定义规则并希望确保它们存在,我有时会写关于在PHP中模拟抽象属性的文章

  4. Improved the mechanism by which validation failure can be determined. If the data validation fails the validation service would throw ValidationException and we can get the errors from that instead of checking for returned data type or values etc. This also means that we can throw another exception if validation rules are not defined. It would be a different exception and we would know immediately that we messed up somewhere.

    改进了可以确定验证失败的机制。 如果数据验证失败,则验证服务将引发ValidationException ,我们可以从中获取错误,而不是检查返回的数据类型或值等。这也意味着,如果未定义验证规则,则可以引发另一个异常。 这将是一个不同的例外,我们会立即知道我们搞砸了某个地方。

  5. Removed the usage of static call for data validation. In here we now inject Laravel’s validation class in our class constructor. If we resolve our validation service out of Laravel’s IoC container (which we would) then we would not have to worry about the dependency injection into constructor here.

    删除了用于数据验证的静态调用的用法。 在这里,我们现在在类构造函数中注入Laravel的验证类。 如果我们从Laravel的IoC容器中解析验证服务(我们会这样做),那么我们就不必担心在这里将依赖项注入到构造函数中。

Now we would create a validation class for our form which would extend this abstract class. In the same directory create TestFormValidator.php and add following code into it:

现在,我们将为表单创建一个验证类,该类将扩展此抽象类。 在同一目录中创建TestFormValidator.php并将以下代码添加到其中:

<?php

namespace RocketCandy\Services\Validation;

class TestFormValidator extends Validator {

	/**
	 * @var array Validation rules for the test form, they can contain in-built Laravel rules or our custom rules
	 */
	public $rules = array(
		'name' => array( 'required', 'alpha_dash', 'max:200' ),
		'email' => array( 'required', 'email', 'min:6', 'max:200' ),
		'phone' => array( 'required', 'numeric', 'digits_between:8,25' ),
		'pin_code' => array( 'required', 'alpha_num', 'max:25' ),
	);

}	//end of class


//EOF

This is the class that we will instantiate to validate our form data. We have set the validation rules in this class and so we would just need to call validate() method on its object and pass our form data to it.

这是我们将实例化以验证表单数据的类。 我们已经在此类中设置了验证规则,因此我们只需要在其对象上调用validate()方法并将表单数据传递给它。

Note: If you have not made the artisan tool in your project directory an executable then you would need to replace ./artisan from the artisan commands in this tutorial and replace with /path/to/php artisan.

注意:如果尚未在项目目录./artisan artisan工具成为可执行文件,则需要从本教程的artisan命令中替换./artisan ,并替换为/path/to/php artisan

It is recommended you make artisan an executable, it saves the needless hassle to prefix php on every command.

建议您将artisan设为可执行文件,这样可以在每个命令的前缀php省去不必要的麻烦。

Let’s make a Controller and a form properly to take this for a spin. In your terminal, navigate to your project directory and run

让我们适当地创建一个Controller和一个表单,以进行旋转。 在您的终端中,导航到您的项目目录并运行

./artisan controller:make DummyController --only=create,store

It would create app/controllers/DummyController.php with two methods – create() and store(). Open up app/routes.php and add the following route directive.

它将使用两种方法创建app/controllers/DummyController.phpcreate()store() 。 打开app/routes.php并添加以下route指令。

Route::resource( 'dummy', 'DummyController', array(
	'only' => array( 'create', 'store' ),
) );

This will set up our Controller to work in a RESTful way; /dummy/create/ would accept GET requests and /dummy/store/ would accept POST requests. We can remove the only directive from both route and artisan command and the Controller would accept PUT and DELETE requests too but for the current exercise we don’t need them.

这将设置我们的控制器以RESTful方式工作; /dummy/create/将接受GET请求, /dummy/store/将接受POST请求。 我们可以从route和artisan命令中删除only指令,并且Controller也将接受PUTDELETE请求,但是对于当前的练习,我们不需要它们。

Now we need to add the code to our Controller, so open up app/controllers/DummyController.php. It would be an empty shell with create() and store() methods. We need to make create() render a view, so make it like this:

现在我们需要将代码添加到Controller中,因此打开app/controllers/DummyController.php 。 这将是带有create()store()方法的空外壳。 我们需要使create()呈现视图,因此使其如下所示:

/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create() {
		return View::make( 'dummy/create' );
	}

We now need the view which we are rendering here and which will render our form.

现在,我们需要在此处呈现的视图以及将呈现表单的视图。

First let’s create a layout file where we can put the HTML boilerplate code. Create layouts directory inside app/views and create default.blade.php inside it. Note the .blade suffix of the view name here. It tells Laravel that this view uses Laravel’s Blade templating syntax and should be parsed as such. Open it up and add the following boilerplate code to it:

首先,让我们创建一个布局文件,在其中放置HTML样板代码。 在app/views创建layouts目录,并在其中创建default.blade.php注意此处的视图名称的.blade后缀。 它告诉Laravel,此视图使用Laravel的Blade模板语法,应按此类进行解析。 打开它,并添加以下样板代码:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">

		<title>Advanced Data Validations Demo</title>

		<!-- Bootstrap core CSS -->
		<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

		<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
		<!--[if lt IE 9]>
			<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
			<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
		<![endif]-->
	</head>

	<body>
		<div class="row">
			<h1 class="col-md-6 col-md-offset-3">Advanced Data Validations Demo</h1>
		</div>
		<p>&nbsp;</p>

		<div class="container">
			@yield( "content" )
		</div><!-- /.container -->

		<!-- Bootstrap core JavaScript -->
		<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
		<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
	</body>
</html>

It is simple boilerplate code for an HTML page which uses Bootstrap. The only thing to notice here is the placeholder where we would inject our view code; @yield( "content" ) will tell Laravel’s Blade parser that our view’s content section code should be injected at this place.

这是使用BootstrapHTML页面的简单样板代码。 这里唯一需要注意的是占位符,我们将在其中插入视图代码。 @yield( "content" )将告诉Laravel的Blade解析器,我们的视图的content部分代码应在此位置注入。

Now create app/views/dummy/create.blade.php and add following code to it:

现在创建app/views/dummy/create.blade.php并向其中添加以下代码:

@extends( "layouts/default" )

@section( "content" )
	<div class="row">
		<h3 class="col-md-6 col-md-offset-2">Test Form</h3>
	</div>
	<p>&nbsp;</p>
	@if ( ! $errors->isEmpty() )
	<div class="row">
		@foreach ( $errors->all() as $error )
		<div class="col-md-6 col-md-offset-2 alert alert-danger">{{ $error }}</div>
		@endforeach
	</div>
	@elseif ( Session::has( 'message' ) )
	<div class="row">
		<div class="col-md-6 col-md-offset-2 alert alert-success">{{ Session::get( 'message' ) }}</div>
	</div>
	@else
		<p>&nbsp;</p>
	@endif

	<div class="row">
		<div class="col-md-offset-2 col-md-6">
			{{ Form::open( array(
				'route' => 'dummy.store',
				'method' => 'post',
				'id' => 'test-form',
			) ) }}
				<div class="form-group">
					{{ Form::label( 'name', 'Name:' ) }}
					{{ Form::text( 'name', '', array(
						'id' => 'name',
						'placeholder' => 'Enter Your Full Name',
						'class' => 'form-control',
						'maxlength' => 200,
					) ) }}
				</div>
				<div class="form-group">
					{{ Form::label( 'email', 'Email:' ) }}
					{{ Form::text( 'email', '', array(
						'id' => 'email',
						'placeholder' => 'Enter Your Email',
						'class' => 'form-control',
						'maxlength' => 200,
					) ) }}
				</div>
				<div class="form-group">
					{{ Form::label( 'phone', 'Phone:' ) }}
					{{ Form::text( 'phone', '', array(
						'id' => 'phone',
						'placeholder' => 'Enter Your Phone Number',
						'class' => 'form-control',
						'maxlength' => 25,
					) ) }}
				</div>
				<div class="form-group">
					{{ Form::label( 'pin_code', 'Pin Code:' ) }}
					{{ Form::text( 'pin_code', '', array(
						'id' => 'pin_code',
						'placeholder' => 'Enter Your Pin Code',
						'class' => 'form-control',
						'maxlength' => 25,
					) ) }}
				</div>
				<div class="form-group">
					{{ Form::submit( '&nbsp; Submit &nbsp;', array(
						'id' => 'btn-submit',
						'class' => 'btn btn-primary',
					) ) }}
				</div>
			{{ Form::close() }}
		</div>
	</div>
@stop

In this view we first tell Laravel that we want to use the default.blade.php layout using the directive @extends( "layouts/default" ). Then we create the content section as that is the one we have set to be injected in the layout. The view renders a form with Name, Email, Phone and Pin Code fields using Laravel’s form builder (we could use HTML5 fields here with the basic browser validation enabled, like for Email we could use Form::email(), but since we want to check our server side validation we are using normal text fields for input). Also above the form we check whether we have anything in the $errors var and to display it if there are any errors. Also we check for any flash message that we might have.

在此视图中,我们首先告诉Laravel我们要使用@extends( "layouts/default" )指令使用default.blade.php布局。 然后,我们创建content部分,因为这是我们设置要注入到布局中的部分。 该视图使用Laravel的表单生成器渲染具有“姓名”,“电子邮件”,“电话”和“密码”字段的表单( 我们可以在此处使用HTML5字段并启用基本的浏览器验证,例如对于电子邮件,我们可以使用Form::email() ,但是由于我们想要要检查我们的服务器端验证,我们使用普通的文本字段输入 )。 同样在表格上方,我们检查$errors变量中是否有任何内容,如果有错误则显示出来。 另外,我们还会检查是否有任何即显信息。

If we now navigate to http://<your-project-domain>/dummy/create (the assumption here is that you have already setup a domain on your development stack for this project) then we will have the form rendered for us. Now we need to be able to accept the data from this form and have the data validated. So back in our DummyController we would inject our TestFormValidator in the constructor and accept the data in store() and validate it. So the Controller would look like this now:

如果现在导航到http://<your-project-domain>/dummy/create ( 此处假设您已经在开发堆栈中为此项目设置了域 ),则将为我们呈现表单。 现在,我们需要能够接受来自此表单的数据并验证数据。 因此,回到DummyController我们将在构造函数中注入TestFormValidator并接受store()的数据并对其进行验证。 因此,控制器现在看起来像这样:

<?php

use RocketCandy\Exceptions\ValidationException;
use RocketCandy\Services\Validation\TestFormValidator;

class DummyController extends BaseController {

	/**
	 * @var RocketCandy\Services\Validation\TestFormValidator
	 */
	protected $_validator;

	public function __construct( TestFormValidator $validator ) {
		$this->_validator = $validator;
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create() {
		return View::make( 'dummy/create' );
	}


	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store() {
		$input = Input::all();

		try {
			$validate_data = $this->_validator->validate( $input );

			return Redirect::route( 'dummy.create' )->withMessage( 'Data passed validation checks' );
		} catch ( ValidationException $e ) {
			return Redirect::route( 'dummy.create' )->withInput()->withErrors( $e->get_errors() );
		}
	}


}	//end of class

//EOF

Laravel will take care of the dependency injection in the constructor as all Controllers are resolved out of its IoC container by default, so we don’t have to worry about that. In the store() method we grab all the form input in a var and inside try/catch we pass the data to our validation service. If the data validates then it will redirect us back to the form page with a success message else it will throw ValidationException which we will catch, grab the errors and return back to the form to display what went wrong.

由于默认情况下所有控制器都是从其IoC容器中解析出来的,因此Laravel将处理构造函数中的依赖项注入,因此我们不必为此担心。 在store()方法中,我们将所有表单输入都try/catch到var中,并在try/catch内部将数据传递给验证服务。 如果数据验证了,它将通过成功消息将我们重定向到表单页面,否则它将抛出ValidationException ,我们将捕获该错误,抓住错误并返回到表单以显示出了什么问题。

摘要 (Summary)

In this first part, we learned how to do data validations the Laravel way and how to abstract out validation to a service which can be used to validate data for each entity anywhere in the app. In the next and final part we will learn how to extend Laravel’s validation package to have our own custom rules.

在第一部分中,我们学习了如何使用Laravel方法进行数据验证,以及如何将验证抽象到服务中,该服务可用于验证应用程序中任何位置的每个实体的数据。 在下一个也是最后一部分,我们将学习如何扩展Laravel的验证包以拥有我们自己的自定义规则。



Got thoughts? Questions? Fire away in the comments.

有想法吗? 有什么问题吗 在评论中开除。

翻译自: https://www.sitepoint.com/data-validation-laravel-right-way/

laravel数据验证

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值