youssefhamdane/validation-rule-generator-fixed

该包最新版本(0.4.0)没有提供许可证信息。

Laravel 4 类,用于根据表结构自动生成验证规则

0.4.0 2020-03-24 19:59 UTC

This package is auto-updated.

Last update: 2024-09-25 05:41:00 UTC


README

此包将自动根据您的模式生成 Laravel 验证规则。它可以生成以下规则的验证

  • 数据库中的所有表
  • 一个(指定的)表
  • 一个(指定的)表中的一个(指定的)列

传递自定义规则以覆盖自动生成的规则。

您可以直接在验证器中使用 ValidationRuleGenerator 的结果,或者您可以从 Artisan 命令中复制它们,并手动将它们输入到您的模型中。

安装

使用 Composer 安装此包。编辑您的 composer.json 文件,以要求 kalani/validation-rule-generator

"require": {
    "laravel/framework": "4.0.*",
    "kalani/validation-rule-generator": "dev-master"
}

接下来,从终端更新 Composer

composer update

最后,将服务提供者添加到 app\config\app.php 中的 providers 数组

'Kalani\ValidationRuleGenerator\ValidationRuleGeneratorServiceProvider',

已经为 ValidationRuleGenerator 设置了一个别名,但如果您想在自己的应用程序中使用一个简短、易于记忆的名称,可以按照以下方式添加另一个别名

'Rules' => 'Kalani\ValidationRuleGenerator\Facades\ValidationRuleGenerator',

(我们将 ValidationRuleGenerator 和 Rules 互换使用)

用法

Artisan 命令

php artisan make:validation 将为指定的表或模型生成规则。这些规则将以您可以直接复制到另一个 PHP 文件中的格式打印出来。

在命令行中,您可以通过以下方式运行规则生成器

php artisan make:validation [--model="..."] [--table="..."] [--all]

以下参数中需要一个

--all               Output table information for all tables in the database
--table=table_name  Returns rules for the given table
--model=ModelName   Returns rules for the given model (with overrides)

如果您传递了 --model 参数,规则生成器将生成模型表的规则,并将其与模型的 $rules 数组合并。在发生冲突的情况下,$rules 数组将占优先权。

直接传递到验证器

调用 ValidationRuleGenerator::getRules($table|$model, $column, $rules, $id)

* `$table`  The name of the table (or model object) for which to get rules
* `$column` The name of the column
* `$rules`  Custom rules (override automatically generated rules)
* `$id`     Ignore unique rules for the given id

所有参数都是可选的。如果不包含任何参数,则该包将返回数据库中所有规则的数组。如果包含 $table,则从该表收集规则;$table 和 $column,则收集给定表/列的规则。

验证表

$valid = Validator::make(Input::all(), Rules::getRules($tableName));

忽略指定 id 验证表

$valid = Validator::make(Input::all(), Rules::getRules($tableName, null, null, $id));

替代用法

在控制器中获取表中所有规则的规则

$rules = ValidationRuleGenerator::getTableRules($model->getTable(), array($custom_rules));
$validation = Validator::make(Input::all(), $rules);

您还可以生成规则以忽略当前记录的 id

$rules = ValidationRuleGenerator::getUniqueRules($rules, $id);

如果您想获取数据库中所有表的验证规则数组

$rules = ValidationRuleGenerator::getAllRules();

如果您想获取一个列的验证规则

$rules = ValidationRuleGenerator::getColumnRules($table, $column);

开发

我们使用 mysql 进行数据库测试,因为 sqlite 不包含许多数据类型。在 mysql 中,创建数据库、用户和密码

CREATE DATABASE test_lrg;
CREATE USER 'test_lrg'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Password1234!';
GRANT ALL ON test_lrg.* TO 'test_lrg'@'localhost';