kalani/validation-rule-generator

此包的最新版本(v0.2.0)没有可用的许可证信息。

Laravel 4 类,基于表架构自动生成验证规则

v0.2.0 2019-02-23 19:45 UTC

This package is auto-updated.

Last update: 2024-09-24 07:36:38 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中的提供者数组中

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