【发布时间】:2020-12-11 13:12:37
【问题描述】:
在文档中找不到任何有关验证集合的信息。在 .NET Core 中,我可以创建一个模型并添加一些数据属性,自动将前端的列表绑定到模型,即使使用 jquery 验证也会显示所有错误。
我想用 Laravel 达到同样的效果
例如在 .NET Core 中,我会有类似的东西
public class Person {
[Required]
public string Name { get; set; }
}
在我要编写的 Razor 页面代码上,这给了我一个可以在我的视图中使用的变量
[BindProperty]
IList<Person> People { get; set; }
那么在我看来,我会像这样渲染它
@foreach(var person in Model.People)
{
<input type="text" asp-for="person.Name" />
}
这会像这样在页面上输出
<input type="text" id="People_0_Name">
<input type="text" id="People_1_Name">
<input type="text" id="People_2_Name">
<input type="text" id="People_3_Name">
这将允许我检查控制器或页面上的模型状态,并自动检查列表中是否有任何错误。一切都做得很好很容易。
现在在 Laravel 上,我是新手,但我已经了解了表单请求和验证规则。
我有表单请求
class CreateContractRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'price' => 'required,
'target' => 'required',
// Want to add a collection here to like, 'people' => 'required
];
}
}
class CreatePeopleRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required'
];
}
}
在 html 中我正在渲染这样的输入
@for($i = 1; $i < $personTotal; $i++)
<input type="text" id="person{{$i}}" name="person{{$i}}">
@endfor
基本上只会渲染
<input type="text" id="person1" name="person1">
<input type="text" id="person2" name="person2">
<input type="text" id="person3" name="person3">
一切都不同。我知道也许我应该为 Person 类创建一个数组并将该变量发送到视图,但我没有使用模型的经验,因为我不需要访问数据库,只需与 API 通信。
总之,我只是想知道如何使数组或集合在 laravel 中更易于使用,从而具有验证规则?
【问题讨论】:
标签: c# php html laravel laravel-blade