search
HomeBackend DevelopmentPHP TutorialExamples of using model validation in Laravel
Examples of using model validation in LaravelOct 26, 2017 am 10:33 AM
laravelmodelvalidation

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

'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);
 } 
}

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

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!

Statement
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
laravel单点登录方法详解laravel单点登录方法详解Jun 15, 2022 am 11:45 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于单点登录的相关问题,单点登录是指在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统,下面一起来看一下,希望对大家有帮助。

一起来聊聊Laravel的生命周期一起来聊聊Laravel的生命周期Apr 25, 2022 pm 12:04 PM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于Laravel的生命周期相关问题,Laravel 的生命周期从public\index.php开始,从public\index.php结束,希望对大家有帮助。

laravel中guard是什么laravel中guard是什么Jun 02, 2022 pm 05:54 PM

在laravel中,guard是一个用于用户认证的插件;guard的作用就是处理认证判断每一个请求,从数据库中读取数据和用户输入的对比,调用是否登录过或者允许通过的,并且Guard能非常灵活的构建一套自己的认证体系。

laravel中asset()方法怎么用laravel中asset()方法怎么用Jun 02, 2022 pm 04:55 PM

laravel中asset()方法的用法:1、用于引入静态文件,语法为“src="{{asset(‘需要引入的文件路径’)}}"”;2、用于给当前请求的scheme前端资源生成一个url,语法为“$url = asset('前端资源')”。

SpringBoot Validation提示信息国际化如何配置SpringBoot Validation提示信息国际化如何配置May 11, 2023 am 11:43 AM

SpringBootValidation支持JSR-380(aka.BeanValidation2.0,partofJakartaEEandJavaSE)注解,可通过验证注解的message属性设置验证错误提示信息,且每个验证注解都有默认的message配置,例如@NotBlank的message属性值设置如下图:默认的message="{...}"的形式即指定国际化属性的名称,后续会根据语言环境替换为对应的值,而这些国际化属性的定义可参见hibernate-validato

Laravel开发:如何使用Laravel Validation验证表单请求?Laravel开发:如何使用Laravel Validation验证表单请求?Jun 13, 2023 pm 01:34 PM

Laravel是一个流行的PHPWeb开发框架,它提供了很多方便的功能来加快开发者的工作。其中,LaravelValidation是一种非常实用的功能,它可以帮助我们轻松地验证表单请求和用户输入的数据。本文就将介绍如何使用LaravelValidation验证表单请求。什么是LaravelValidationLaravelValidation是La

实例详解laravel使用中间件记录用户请求日志实例详解laravel使用中间件记录用户请求日志Apr 26, 2022 am 11:53 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于使用中间件记录用户请求日志的相关问题,包括了创建中间件、注册中间件、记录用户访问等等内容,下面一起来看一下,希望对大家有帮助。

laravel中间件基础详解laravel中间件基础详解May 18, 2022 am 11:46 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于中间件的相关问题,包括了什么是中间件、自定义中间件等等,中间件为过滤进入应用的 HTTP 请求提供了一套便利的机制,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools