Laravel learning tutorial model validation example, laravelvalidation

Source: Internet
Author: User

Laravel learning tutorial model validation example, laravelvalidation

Preface

This article mainly introduces the use of model validation in Laravel learning and shares the content for your reference. I will not talk about it much below. Let's take a look at the detailed introduction.

Before writing data to a database, validate the data. For example, type-check defines each model column (the 'type' column must beenum('card','loan')) Here, we use model event.

In EventServiceProvider (or custom ValidationServiceProvider), write:

public function boot(){  /**   * Inspired by @see \Illuminate\Foundation\Providers\FormRequestServiceProvider::boot()   *   * Note: saving event is always triggered before creating and updating events   */  $this->app['events']->listen('eloquent.saving: *', function (string $event_name, array $data): void {   /** @var \App\Extensions\Illuminate\Database\Eloquent\Model $object */   $object = $data[0];      $object->validate();  });}

'eloquent.saving: *'Indicates the saving of all listen models. That is, the write operation of any model triggers this event.

Then write an abstract model extends EloquentModel:

// \App\Extensions\Illuminate\Database\Eloquent\Modeluse Illuminate\Database\Eloquent\Model as EloquentModel;use Illuminate\Validation\ValidationException;abstract class Model extends EloquentModel{ public function validate():void {  // 1. validate type rules (type-check)  $validator = $this->getTypeValidator();    if ($validator->fails()) {   throw new ValidationException($validator);  }    // $validator = $this->getConstraintValidator();  // 2. validate constraint rules (sanity-check) } protected function getTypeValidator() {  return $this->getValidationFactory()->make($this->attributes, static::COLUMN_TYPE_RULES); }  protected function getValidationFactory() {  return app(Factory::class); }  protected function getConstraintValidator() {  // return $this->getValidationFactory()->make($attributes, static::COLUMN_CONSTRAINT_RULES); } }

In this way, define const COLUMN_TYPE_RULES in each subclass that inherits abstract model, such:

class Account extends Model{ public const COLUMN_TYPE_RULES = [  'id' => 'integer|between:0,4294967295',  'source' => 'nullable|in:schwab,orion,yodlee',  'type' => 'required|in:bank,card,loan', ];}

During the write operation, type-check is performed on schema definition of each model in advance to avoid database collisions. The purpose of this feature is to verify from the model schema whether the field definition of the input data is legal.

In addition to type-check schema definition, you also need to perform logical validation sanity-check constraint rules based on business needs. For example, when creating an account, the personal _id field in the input inputs cannot be a child minor, and so on. Here the business is different, and the constraint rules is different, so we will not explain it too much. This feature is designed to logically verify the legitimacy of input data.

OK. In general, model validation is required before writing to the database to avoid invalid hit db.

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.