Examples of using model validation in Laravel

黄舟
Release: 2023-03-16 19:20:01
Original
2131 people have browsed it

Preface

This article mainly introduces to you the relevant content about the use of model validation in Laravel learning, and shares it for your reference and study. I won’t say much more below. Let’s take a look at the detailed introduction.

Before writing to the database, the data needs to be verified, such as type-check. The definition of each model column ('type' this column must be enum('card','loan' )) , model event is used here.

Write in EventServiceProvider (or customize a ValidationServiceProvider):

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();
  });
}
Copy after login

'eloquent.saving: *' means listening to the saving of all models, that is, the write operation of any model will trigger this event.

Then write an abstract model extends EloquentModel:

// \App\Extensions\Illuminate\Database\Eloquent\Model

use 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);
 } 
}
Copy after login

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

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',
 ];
}
Copy after login

When writing , type-check the schema definition of each model in advance to avoid invalid collisions with the database. The purpose of this feature is to verify whether the field definitions of the input data are legal from the model schema.

In addition to the type-check schema definition, the logic check sanity-check constraint rules must be carried out according to business needs. For example, when creating an account, the field person_id in the inputs cannot be child. Minors, etc. The business here is different and the constraint rules are different, so I won’t explain too much. The purpose of this feature is mainly to logically verify the legality of the input data.

OK, in short, under normal circumstances, model validation needs to be done before writing to the database to avoid invalid hit db.

Summarize

The above is the detailed content of Examples of using model validation in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!