regulus / formation
一个强大的表单构建和模型数据转换包,适用于 Laravel 5 - 8。
Requires
- php: ^8.1
- laravel/framework: >=10.0.0
- regulus/tetra-text: 0.6.*
Suggests
- regulus/elemental: 0.5.*
- dev-master
- v1.6.0
- v1.5.1
- v1.5.0
- v1.4.14
- v1.4.13
- v1.4.12
- v1.4.11
- v1.4.10
- v1.4.9
- v1.4.8
- v1.4.7
- v1.4.6
- v1.4.5
- v1.4.4
- v1.4.3
- v1.4.2
- v1.4.1
- v1.4.0
- v1.3.20
- v1.3.19
- v1.3.18
- v1.3.17
- v1.3.16
- v1.3.15
- v1.3.14
- v1.3.13
- v1.3.12
- v1.3.11
- v1.3.10
- v1.3.9
- v1.3.8
- v1.3.7
- v1.3.6
- v1.3.5
- v1.3.4
- v1.3.3
- v1.3.2
- v1.3.1
- v1.3.0
- v1.2.9
- v1.2.8
- v1.2.7
- v1.2.6
- v1.2.5
- v1.2.4
- v1.2.3
- v1.2.2
- v1.2.1
- v1.2.0
- v1.1.10
- v1.1.9
- v1.1.8
- v1.1.7
- v1.1.6
- v1.1.5
- v1.1.4
- v1.1.3
- v1.1.2
- v1.1.1
- v1.1.0
- v1.0.7
- v1.0.6
- v1.0.5
- v1.0.3
- v1.0.2
- v1.0.1
- v1.0.0
- v0.9.4
- v0.9.0
- v0.7.0
- v0.6.0
- dev-dependabot/composer/laravel/framework-5.8.38
This package is auto-updated.
Last update: 2024-09-24 00:27:01 UTC
README
一个强大的表单构建和模型数据转换包,适用于 Laravel 11(支持从 Laravel 5 开始的版本)。
Formation 由两个独立但互补的系统组成,可以独立使用
-
一个强大的表单构建器,它使使用 PHP 表单构建方法自动构建表单变得非常容易
-
一个易于使用的可扩展 Eloquent(或可选地使用
Extended
特性)的数据转换器基本模型,它提供许多数据转换功能,无论是从 Web 服务器向客户端提供服务,还是将表单数据保存到数据库中。
- 安装
- 1. 表单构建器
- 示例路由
- 打开表单
- 默认表单值
- 验证规则
- 标签
- 文本、文本区域、密码和隐藏字段
- 文件输入
- 复选框和单选按钮
- 复选框和单选按钮组
- 下拉列表
- 文件输入
- 按钮
- 字段方法
- 2. 数据转换器基本模型和扩展特性
- 包含数组和属性集的方法
- 格式化数据以便保存到数据库
注意: 所有在表单元素中显示的输入数据都通过实体方法进行过滤。
安装
要安装 Formation,请运行 composer require regulus/formation
或将 regulus/formation
添加到 Laravel 的 composer.json
文件中
"require": {
"regulus/formation": "1.6.*"
},
然后从命令行运行 php composer.phar update
。Composer 将安装 Formation 包。现在,您只需在 config/app.php
中注册服务提供程序并设置 Formation 的别名即可
Regulus\Formation\FormationServiceProvider::class,
在 bootstrap/providers.php
中的数组中添加此内容
$loader->alias('Form', \Regulus\Formation\Facade::class);
Formation 现已就绪。现在,只需从命令行发布配置文件 form.php
以及您需要的视图和 JS 文件
php artisan vendor:publish
1. 表单构建器
表单构建器的以下是一些精选功能:- 使用数据填充表单(默认值和 POST 数组提供的数据)- 向标签和表单字段添加 error
类- 根据字段名称添加 ID 到表单字段,并为字段的标签添加匹配的 for
属性- 提供验证 POST 数组中特定数组以及整个表单的能力- 默认使用 Twitter Bootstrap 4 类为表单元素设置,但可以轻松地定制其他 CSS 框架- 允许使用 PHP 和 JS 的组合,以自动创建 Handlebars JS 表单模板
所有这些都可以用最少的代码实现
{!! Form::field('first_name') !!}
{!! Form::field('password') !!}
{!! Form::field('user.item', 'select', [
'options' => prep_options(Item::all(), ['id', 'name'])
]) !!}
简单地输出 Form::field('first_name')
与以下代码相同
<div class="form-group" id="field-first-name-area"> {!! Form::label('first_name') !!} {!! Form::text('first_name') !!} {!! Form::error('first_name') !!} </div>
以上代码可能产生以下标记
<div class="form-group has-error" id="field-first-name-area"> <label for="field-first-name" class="control-label has-error"><span class="access">F</span>irst Name</label> <input type="text" name="first_name" id="field-first-name" class="form-control has-error" placeholder="First Name" accesskey="f" value="Joe" /> <div class="error">The First Name field is required.</div> </div>
以上代码展示了Formation如何简单且通用。顶部三个字段利用了Formation的简化版field()
方法,中间部分展示了如何通过较长的方式实现前两个文本字段相同的标记,最后部分展示了从以上两个示例中可能产生的标记(假设已为"first_name"字段设置了一个"required"表单验证规则,并且已提交表单)。您可能会注意到标记相当全面和完整。访问键会自动使用(除非您另行指定),并且将"access"类应用于标签中的访问键字母。标签、字段以及可能还有错误都被包裹在一个带有Twitter Bootstrap "form-group"类的div标签中。ID基于名称,但使用连字符代替下划线,标签也自动从名称中创建(但也可以手动指定)。所有字段在表单数据发布到页面时都将自动重新填充。字段、标签、错误、容器以及ID/类前缀的类可以在配置文件中进行自定义。
<input name="user[name]" value="" /> <input name="user[email]" value="" /> <input name="other_field" value="" />
使用此表单,我们可以使用Form::isValid('user')
验证用户数组中的字段,使用Form::isValid('root')
验证最后一个字段,或者使用Form::isValid()
验证表单中的所有字段。
示例路由
如果您在config/form.php
中将example_routes
设置为true
,或者将其设置为null
,并在.env
中将APP_ENV
变量设置为除production
之外的内容,您就可以访问/formation
来加载示例视图,并查看Formation的实际应用。建议您结合文档一起查看,以便更好地了解Formation的可用性和工作原理。
打开表单
在当前URL上打开表单进行POST
{!! Form::open() !!}
使用给定的URI和请求方法打开表单
{!! Form::open(['url' => user/profile']) !!}
打开接受文件上传的表单
{!! Form::openForFiles(['url' => 'user/profile', 'files' => true]) !!}
打开资源控制器表单
{!! Form::openResource() !!}
注意:此方法自动为表单操作创建正确的路由,假设正在使用资源控制器。
关闭表单
{!! Form::close() !!}
默认表单值
Formation最有用的功能之一是它能够接受一个数组、对象或Eloquent模型,并自动使用它来填充表单字段。当表单被提交时,它将自动使用POST数组中的值。
$defaults = [ 'name' => 'Ron Paul', 'email' => 'ron@paul.com', 'active' => true, ]; Form::setDefaults($defaults);
注意:如果您想使用数组字段名称,请使用,例如,
user.name
和user.email
代替name
和
即使在表单POST之后也强制使用默认值
Form::resetDefaults();
使用关系设置默认值
$user = User::find(1); Form::setDefaults($user, ['posts']);
这将为用户模型中定义的posts
关系自动设置默认值。
根据特定属性设置基于关系的默认值
$user = User::find(1); Form::setDefaults($user, [ 'posts' => '*', 'roles' => 'id', ]);
与上面的示例类似(尽管这是相同内容的关联数组版本),而roles
项将只选择关系的id
属性添加到默认值数组中。这可以用于带有roles.
名称前缀的复选框集,以管理在belongsToMany()
关系中的记录选择。以下复选框和单选按钮集
部分有一个示例。
验证规则
Formation 使用 Laravel 的 Validator 类。使用 Form::setValidation()
将创建 Validator 类的实例(如果表单设置中使用数组字段名,则可以创建多个实例)。将表单验证规则传递给 Formation 以通过 Validator 的原因是 Formation 会自动在发生错误时向标签和表单字段添加 "error" 类。为了这样做,Formation 需要验证规则的一个副本。
$rules = [ 'user.name' => ['required'], // 'user.name' can be used for an array field like "user[name]" 'email' => ['required', 'email'] ]; Form::setValidationRules($rules);
验证所有字段
if (Form::isValid()) { return true; }
验证数组中的字段
if (Form::isValid('user')) // validates array fields with names like "user[name]" and "user[email]" { return true; } if (Form::isValid('user.')) // ending with a "." allows us to validate fields like "user[0][name]" and "user[1][name]" { return true; }
最后一个示例可以在你有很多类似于上面 user
的数组字段实例时使用。该示例将验证 Input::get('user')
的所有子字段。以点结尾的名称让 Formation 知道 user
是一个可能包含多个相同子字段集合的数组。
标签
使用数组设置标签
$labels = [ 'name' => 'Name', 'email' => 'Email Address', ]; Form::setLabels($labels);
通过使用数组设置你的标签,你将能够在 Form::label()
中将第二个参数设置为 null
。
生成标签元素
{!! Form::label('email', 'Email Address') !!}
如果你不传递第二个参数的标签,它将在 Formation 的 $labels
数组中查找,该数组可以通过 Form::setLabels()
设置。如果在这里找不到,它将从第一个参数中的字段名推断出来。
为标签指定额外的 HTML 属性
{!! Form::label('email', 'Email Address', ['class' => 'email']) !!}
注意:创建标签后,任何具有与标签名称匹配名称的表单元素都将自动接收与标签名称匹配的 ID。名称中的下划线在 ID 中总是被替换为破折号。
文本、文本区域、密码和隐藏字段
生成文本输入元素
{!! Form::text('username') !!}
指定文本输入元素的默认值
{!! Form::text('email', ['value' => 'example@gmail.com']) !!}
设置文本字段的属性
{!! Form::text('user.first_name', ['class' => 'short']) !!}
通过使用 Form::setDefaults()
,你不需要传递默认值,而是可以将第二个参数传递为 null
或不传递任何值,以让字段利用预设的默认值。除非使用 Form::resetDefaults()
,否则在表单提交时将使用 POST 数组中的值。
注意:名称属性为
first_name
的字段将自动赋予first-name
的 ID。名称中的下划线在 ID 中总是被替换为破折号。
在保留唯一 ID 的同时为文本字段命名而不指定数组索引
{!! Form::text('user.(0).username') !!}
上面的示例将创建一个名称为 user[][username]
且 ID 为 user-0-username
的文本字段。如果你希望显式指定名称的索引,只需省略圆括号即可。
{!! Form::text('user.0.username') !!}
生成密码输入元素
{!! Form::password('password') !!}
复选框和单选按钮
生成复选框输入元素
{!! Form::checkbox('name', ['value' => 'X']) !!}
生成带标签的复选框输入元素
{!! Form::checkbox('name', ['label' => true]) !!}
{!! Form::checkbox('name', ['label' => 'Custom Label']) !!}
{!! Form::checkbox('name', ['label' => 'Custom Label', 'label-first' => true]) !!}
生成默认选中的复选框
{!! Form::checkbox('name', ['checked' => true]) !!}
注意:一旦你通过 Form::setDefaults()
设置了默认值,你将不需要第二个参数来设置值。
注意:单选按钮方法与复选框方法的签名相同。一石二鸟!
复选框和单选按钮组
创建一组复选框
<?php $checkboxes = simple_options(['Rain', 'Thunder', 'Lightning']); ?>
{!! Form::checkboxSet($checkboxes) !!}
为每个复选框的名称添加前缀
{!! Form::checkboxSet($checkboxes, ['name-prefix' => 'weather']) !!}
在此示例中,所有复选框的名称属性都将为 weather[]
。
使用显式键为每个复选框的名称添加前缀
{!! Form::checkboxSet($checkboxes, ['name-prefix' => 'weather', 'explicit-keys' => true]) !!}
{!! Form::checkboxSet($checkboxes, ['name-prefix' => 'weather.']) !!}
这两个示例都将生成类似于 weather[Thunder]
的名称属性。包括一个 .
字符自动使用显式键,但你也可以将其作为属性传递以更容易理解所发生的事情。
强制将复选框选项解释为关联数组
{!! Form::checkboxSet($checkboxes, ['associative' => true]) !!}
默认情况下,checkboxSet()
将你的数组解释为关联数组,除非键是整数,或者键是评估为正整数的字符串,但你可以通过传递一个 associative
布尔值来强制它以任何方式解释复选框选项。
指定用作复选框值的对象
<?php $checkboxes = [ 'checkbox_name' => 'Checkbox Label!', 'checkbox_name2' => 'Checkbox Label 2!', ]; ?>
{!! Form::checkboxSet($checkboxes, ['name-values' => true]) !!}
{!! Form::checkboxSet($checkboxes, ['label-values' => true]) !!}
默认情况下,复选框的值是简单的 1
,但你可以设置复选框集使用名称作为值(关联数组的键)或使用标签作为值(关联数组的值)。
管理多对多关系中的选择
$user = App\Models\User\User::find(1); Form::setDefaults($user, [ 'roles' => 'id', ]); $roleOptions = prep_options(App\Models\User\Role::get(), ['id', 'name']);
{!! Form::checkboxSet($roleOptions, [
'name-prefix' => 'roles',
'associative' => true,
'name-values' => true,
]) !!}
向复选框和/或无序列表容器添加属性
{!! Form::checkboxSet($checkboxes, [
'class' => 'weather',
'id-container' => 'checkbox-set-weather',
]) !!}
注意:以 "-container" 结尾的属性将添加到容器本身,而不是添加到每个复选框。
创建一组单选按钮
{!! Form::radioSet('weather', simple_options(['Rain', 'Thunder', 'Lightning'])) !!}
注意:在上面的例子中,
simple_options()
方法仅用于使单选按钮的标签也用作实际的表单字段值,而不是使用数组项的数字索引。simple_options()
以及一些其他构建选项的方法将在文档的 下拉列表 部分进一步描述。
您可以将 "-container" 添加到属性名称中,以便将它们分配给单选按钮集的容器元素。单选按钮和复选框的默认容器类分别是 radio-set
和 checkbox-set
。容器是无序列表元素,集合中的每个项目都是列表中的一个列表项。
下拉列表
从项目数组生成下拉列表
{!! Form::select('size', ['L' => 'Large', 'S' => 'Small']) !!}
使用空值的标签作为列表中的第一个选项
{!! Form::select('size', ['L' => 'Large', 'S' => 'Small'], ['null-option' => Select a Size']) !!}
生成具有默认选中选项的下拉列表
<?php // you may pass either a "selected" or "value" attribute to select an option ?>
{!! Form::select('size', ['L' => 'Large', 'S' => 'Small'], ['null-option' => 'Select a Size', 'value' => 'S']) !!}
{!! Form::select('size', ['L' => 'Large', 'S' => 'Small'], ['null-option' => 'Select a Size', 'selected' => 'S']) !!}
当然,您可以使用 Form::setDefaults()
来填充选择框,而无需设置第三个 selected
或 value
属性。
将数组、对象或 Eloquent 集合转换为选项集
$users = DB::table('users')->orderBy('username')->get();
{!! Form::select('user', prep_options($users, ['id', 'username']), 'Select a User') !!}
将简单的数组转换为具有与标签相同值的选项数组
{!! Form::select('animal', simple_options(['Tiger', 'Zebra', 'Elephant']), ['null-option' => Select an Animal']) !!}
将简单的数组转换为具有与标签相同值的选项数组,除了小写
{!! Form::select('animal', simple_options(['Tiger', 'Zebra', 'Elephant'], true), ['null-option' => Select an Animal']) !!}
将简单的数组转换为具有从一开始的数字的简单选项数组
{!! Form::select('animal', offset_options(['Tiger', 'Zebra', 'Elephant']), ['null-option' => Select an Animal']) !!}
将简单的数组转换为具有从一开始的数字的简单选项数组
<?php // display options from 0 to 180 incrementing by 10 each time ?>
{!! Form::select('number', number_options(0, 180, 10)) !!}
第一个参数是起始数字,第二个参数是结束数字,第三个参数是迭代的数字。如果是负数,您可以向下计数而不是向上。最后,第四个参数用于表示数字应该有多少小数位。
创建月份的选项数组
<?php // count up 12 months from current month ?>
{!! Form::select('month', month_options('current', 12)) !!}
<?php // count down 12 months from current month ?>
{!! Form::select('month', month_options(true, -12)) !!}
<?php // count up to a specific month from current month ?>
{!! Form::select('month', month_options(true, '2013-04-08')) !!}
<?php // count down to a specific month from another specific month ?>
{!! Form::select('month', month_options('2013-11-11', '2013-04-08')) !!}
<?php // count down 12 months from current month and use the last day of the month for "month_end" field ?>
{!! Form::select('month_start', month_options(true, -12, false, 'M Y')) !!}
{!! Form::select('month_end', month_options(true, -12, true, 'M Y')) !!}
第一个参数是你的起始月份。您可以使用 true
、false
、null
或 "current" 来使用当前月份。第二个参数可以有一个正数或负数整数来向上或向下计数特定数量的月份,或者可以有一个日期字符串来向上或向下计数月份直到特定日期。如果第三个参数 endDate
设置为 true,则用于选项值的日期将使用月份的最后一天而不是第一天。最后,您可以将日期格式作为选项标签的第四个参数指定。默认是 "F Y"。
注意:上述所有选项数组构建函数也可以用于复选框集和单选按钮集,并且是包装核心 Formation 函数的帮助函数。例如,
prep_options()
使用Form::prepOptions()
。
使用字段宏为单选按钮集
<?php $options = simple_options(['T-Rex', 'Parasaurolophus', 'Triceratops']); ?>
{!! Form::field('dinosaur', 'radio-set', ['label' => 'Favorite Dinosaur', 'options' => $options]) !!}
文件输入
生成文件输入元素
{!! Form::file('image') !!}
按钮
生成提交按钮元素
{!! Form::submit('Click Me!') !!}
如果您没有设置第一个参数,将使用 "Submit" 作为标签。
注意:需要创建一个按钮元素?尝试按钮方法。它具有与提交相同的签名。
字段方法
您可以使用内置的 Form::field()
方法将此转换为
<div class="form-group" id="user-email-area"> {!! Form::label('user.email') !!} {!! Form::text('user.email') !!} {!! Form::error('user.email') !!} </div>
变成这样
{!! Form::field('user.email') !!}
字段容器元素可以从 div 更改为其他 HTML 元素,并在 config.php
中更改 "form-group" 类。如果您根本不想使用字段容器,您可以使用以下方法
{!! Form::field('name', 'text', ['field-container' => false]) !!}
使用字段方法为下拉选择框
{!! Form::field('animal', 'select', [
'options' => simple_options(['Tiger', 'Zebra', 'Elephant'])
]) !!}
使用字段方法为单选按钮集
<?php $options = simple_options(['T-Rex', 'Parasaurolophus', 'Triceratops']); ?>
{!! Form::field('dinosaur', 'radio-set', ['label' => 'Favorite Dinosaur', 'options' => $options]) !!}
使用字段方法为复选框集
{!! Form::field('number.', 'checkbox-set', [
'options' => offset_options(['One', 'II', '3.0'])
]) !!}
您会注意到第三个参数 attributes
包含一些特殊属性的选项,例如 label
和 options
,它们的工作方式与其他属性声明不同。将这些属性组合到属性数组中是有意义的,因为字段方法具有通用和多功能的特点。这避免了简单字段需要大量 null
参数。除了 label
和 options
,您还可以使用 null-option
为下拉框添加前置的空选项。最后,value
可以用来手动设置字段的值。如果您使用 setDefaults()
或 setup
方法预先填充表单数据,则此操作是不必要的。
$attributes = [ 'class' => 'select-number', 'options' => number_options(1, 10), 'null-option' => 'Select a Number', 'value' => 3, ];
{!! Form::field('number', 'select', $attributes) !!}
注意:以 "-container" 结尾的属性将添加到容器本身,而不是字段。以 "-label" 结尾的属性将添加到字段的标签。
2. 数据转换器基本模型和扩展特性
Formation 包含一个基本模型,它简单地扩展了 Eloquent 的 Model
类,并使用一个包含许多高级模型特性的 trait,特别是在为通过 API 提供服务或格式化数据库保存前数据的方式。您可以直接从您的模型(Regulus\Formation\Models\Base
)扩展 Base
模型,或者仅使用现有的模型中的 Extended
trait(Regulus\Formation\Traits\Extended
)。
包含数组和属性集的方法
包含在数组中的方法
您可以在模型中添加一个 protected static $arrayIncludedMethods
数组来指定您希望在模型通过 toArray()
或 toJson()
运行时包含的方法。当使用 Vue 等前端 JS 框架时,这非常有用。Laravel 的 Eloquent 模型系统已经包含 appends
数组用于此目的,但这是一个更灵活的方法,因为它允许您传递参数,并为字段命名。
protected static $arrayIncludedMethods = [ 'name' => 'getName(true)', 'url' => 'getUrl', // parameters not required ];
属性集
您可以在模型中添加一个 protected static $attributeSets
数组来定义特定的属性集,用于通过 toArray()
或 toJson()
返回,可以通过 getAttributeSet()
和集的名称(您数组的键)来获取。这允许您为不同的目的定义不同的属性集。您还可以在相关内容中引用集合。以下是一个完整示例。假设我们有一个名为 Post
的模型,它通过 author()
关系属于 User
,并且该模型具有以下属性集
/** * The attribute sets for the model. * * @var array */ protected static $attributeSets = [ 'standard' => [ 'id', 'content', 'url', // this could even be a key listed in $arrayIncludedMethods for a getUrl() method ], 'update' => [ 'set:standard', // include all attributes in "standard" set 'attribute:content', // set "content" attribute to ignore array-included method in favour of actual value from DB ], ]; /** * The attribute sets for related models. * * @var array */ protected static $relatedAttributeSets = [ 'standard' => [ 'author' => 'set:author', // this will use an attribute set from the model used for the "author" relationship 'section' => 'class:'.Section::class, // this will look for an attribute set called "standard" 'tags' => 'class:'.Tag::class.';set', // this will look for an attribute set called "set" ], ];
在我们的用户模型中,我们定义了以下包含在数组中的方法和属性集
/** * The methods to automatically include in a model's array / JSON object. * * @var array */ protected static $attributeSets = [ 'author' => [ 'id', 'username', 'select:first_name', // this data is only being selected, and will be combined using the "getName" method defined above 'select:last_name', // this data is only being selected, and will be combined using the "getName" method defined above 'name', ], ]; /** * The attribute sets for the model. * * @var array */ protected static $arrayIncludedMethods = [ 'name' => 'getName', ];
注意:如果您直接使用扩展特质而不是扩展 Base 模型,则必须将所有转换配置放在一个名为
$transformConfig
的单个静态数组中,因为您不能覆盖特质的静态变量(此格式也适用于扩展 Base 模型,但在那种情况下不是必需的)
/** * The data transforming configuration. * * @var array */ public static $transformConfig = [ 'arrayIncludedMethods' => [ // ], 'attributeSets' => [ 'standard' => [ // ], ], 'relatedAttributeSets' => [ 'standard' => [ // ], ], ];
现在,我们可以查询具有 author
关系的 Post
模型,并将其作为 JSON 数据返回
$post = Post::selectAttributeSet('standard') ->limitRelatedData() ->first(); // selectSet is short-hand alias for selectAttributeSet $users = User::selectSet('author', true), passing true as the second parameter automatically calls limitRelatedData() scope ->get() ->toArray();
上面的示例实际上并不需要使用standard
参数,因为它们是各自函数的默认值。selectAttributeSet()
/ selectSet()
使用了getAttributeSet()
,但默认情况下也使用“select”属性集键(如果“select”不可用,则回退到“standard”),并在可能的情况下添加一个表前缀(如果您在使用具有模糊列名的JOIN)。它还移除了用于表示要选择但不返回在数组中的字段的select:
前缀(对于底层列用于数组包含方法的场景)。如果您有一个与使用数组包含方法的动态属性同名属性,您可以在属性集中添加一个attribute:
前缀,以使toArray()
使用原生属性而不是动态创建的属性。
这将使我们能够大幅度减少返回的数据量,以便我们仅获取所需的数据而无需更多
注意:如果您使用
selectAttributeSet()
/selectSet()
或limitRelatedData()
作用域,在模型实例、集合或分页器上调用toLimitedArray()
将使用之前提供的任何属性集。
{ "id":343, "content":"Taxation is theft, purely and simply even though it is theft on a grand and colossal scale which no acknowledged criminals could hope to match. It is a compulsory seizure of the property of the State's inhabitants, or subjects.", "created_at":"1973-03-02 00:00:00", "author":{ "id":1, "username":"ForANewLiberty", "name":"Murray Rothbard" } }
您还可以在toArray()
方法中指定属性集,或使用toLimitedArray()
,它只是将standard
作为第一个参数自动选择标准属性集。
return $post->toArray('standard'); return $post->toLimitedArray(); // same as above, assumes "standard" by default return Post::orderBy('id')->get()->toArray('standard'); // filter models in a collection with attribute set
最后,Record::getAttributeSet('fillable')
将返回“id”属性以及模型$fillable
数组中列出的任何内容。
将分页器转换为数组
Extended
特质使用Formation中所有与模型相关的Laravel类的所有扩展。这意味着toArray()
和toLimitedArray()
对模型实例本身、模型集合以及从模型的paginate()
方法创建的分页器都可用。
return Post::orderBy('id')->paginate(25)->toArray('standard'); // return a paginator converted to an array return Post::orderBy('id')->setPage(3)->paginate(25)->collectionToArray('standard'); // return just the collection
注意:
toLimitedArray()
和collectionToLimitedArray()
也可以用于默认属性集为“standard”。
格式化数据以便保存到数据库
类型
您可以在模型中添加一个protected static $types
数组,以允许在填充表单之前或将数据保存到数据库之前自动格式化数据。以下类型可以使用:
- 复选框
- 日期
- 日期时间
- 日期时间戳
- 时间戳
- 非空日期
- 非空日期时间
- 非空日期时间戳
- 非空时间戳
- 令牌(仅在记录创建时设置,默认长度为32,但可以设置自定义长度,例如
token:16
) - 别名
- 唯一别名
- 复选框时间戳(如果字段是
active
,则保存的时间戳变为active_at
,但您也可以指定自定义字段,例如checkbox-timestamp:activated_at
)
注意:您可以参考
Regulus\Formation\Traits\Extended
特质中的示例以及所有其他辅助数组。特质包含针对每个数组的注释掉的数组示例。
格式
您可以在模型中添加protected static $formats
和protected static $formatsForDb
数组,以在填充表单或数据保存之前进行一些额外的自动数据格式化。
/** * The special formatted fields for the model for saving to the database. * * @var array */ protected static $formatsForDb = [ 'media_type' => 'null-if-false:media', 'published_at' => 'null-if-false:published', ];
以下格式可以使用:
- 如果为null则返回false
- 如果为null则返回true
- 如果不为null则返回false
- 如果不为null则返回true
- 如果为空则返回false
- 如果为空则返回true
- 如果为空则返回null
- 如果不为空则返回false
- 如果不为空则返回true
- 如果不为空则返回null
- 如果已设置则返回false
- 如果为true则返回false
- 如果已设置则返回true
- 如果为true则返回false
- 如果已设置则返回null
- 如果为true则返回null
- 如果没有设置则返回false
- 如果没有设置则返回false
- 如果没有设置则返回true
- 如果没有设置则返回true
- 如果没有设置则返回null
- 如果没有设置则返回null
- JSON
- JSON或null
- 去除空格
- 首字母大写
- 单词首字母大写
- 全部大写
- 全部小写
在保存到数据库之前,使用 formatSave()
或 formatCreate()
方法时,$types
、$formats
和 $formatsForDb
的格式将自动进行。您也可以通过使用模型或特质自己的 setDefaults()
方法来运行它们。或者,您可以使用 getFormattedValues()
获取格式化值的数组。许多格式选项,如 null-if-not-set
,将允许您传递一个已检查的字段,即使要检查的字段不是应用格式规则的字段。例如,如果您有一个名为 location_info
的字段,您可以设置 null-if-not-set:location
,这样如果 POST 数据中没有设置 location
布尔值,则 location_info
将被更改为 null
。
格式化与保存数据
设置完上述格式后,您可以使用 $record->formatSave()
和 Record::formatCreate()
自动格式化数据并保存。如果您在模型中设置了一个 formatValuesForModel()
方法,您可以在 $types
、$formats
和 $formatsForDb
数组中添加自定义格式化规则。此外,您可以在 executeSaveTriggers($create = false)
方法中添加额外的保存后逻辑(用于在关系中的相关数据或执行需要首先存在记录的其他操作)。
验证
您始终可以使用 Form::setValidationRules($rules, $input)
,但如果您使用基本模型或特质,您可以在模型中定义一个 validationRules($record = null, $input = null, $action = null)
函数后执行以下任何一项。建议您从扩展特质复制一个空白的作为起点。第三个参数,$action
,默认不使用,但存在以提供根据不同的数据更新操作设置不同验证规则的能力。如果您的模型中设置了此方法,您可以使用以下任何一种方法来设置验证规则:
// new record Form::setValidationRulesForNew($input); // existing record $record->setValidationRules($input); // new or existing record ($record can be null) Form::setValidationRulesForModel($record, $input);
注意:如果您想使用所有输入值,不需要传递
$input
,它将默认为Input::all()
。