spmsupun/validation-rule-generator

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

0.0.2 2018-09-03 10:22 UTC

This package is not auto-updated.

Last update: 2024-09-25 14:05:14 UTC


README

此Laravel 4包将自动根据您的架构生成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 generate:rules将生成给定表或模型的规则。这些规则将以您可以直接复制到其他PHP文件中的格式打印。

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

php artisan generate:rules [--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);