这一直让我疯狂!!
我的表单会创建用户。创建这些用户的管理员可以添加多行输入,然后在最后保存所有内容。我在jQuery中使用clone()方法,我已经对所需的输入进行了客户端验证等...我有一个非常强大的Domain层,但现在我需要服务器端验证,以便Laravel可以检查是否电子邮件已存在,因为它必须是唯一的。我非常精通Laravel,但是对于新的FormRequest对象,我仍然坚持如何遍历每个输入等,因为FormRequestObject似乎只接受一个条目。这一切都在阿贾克斯......
我的formData如下所示:
counter:2
_token:KwGAUheSXbzkInh1RZ4RPenx4Fd4fF5DsPm5bjyO
firstname_1:name1
lastname_1:last1
email_1:email@email.com
password_1:keith
firstname_2:name2
lastname_2:last2
email_2:email@email.com
password_2:keith
您可以输入名称具有递增ID,因此表单请求中的rules()必须遍历这些。我真的卡住了,在网上找不到一个例子。
我的表单reuqest类看起来像这样:
<?php namespace hidden\Http\Controllers\UserAccess\Requests;
use hidden\Http\Requests\Request;
use Illuminate\Auth\Guard;
use hidden\Domain\Services\UserAccess\GetUserFromEmailService;
class CreateAdministratorRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required'
];
}
}
到目前为止我的控制器方法(它最终将遍历输入并发送命令,但此刻毫无意义):
/**
* @param CreateAdministratorRequest $request
*/
public function createAdministrators(CreateAdministratorRequest $request)
{
// dispatch command per entry
}
答案 0 :(得分:2)
如果您想尽可能保持结构,可以执行以下操作。
public function rules()
{
$counter = $this->get('counter');
$emails= [];
// validate manually if every submitted email is unique
// so, we need every email value
for ($i = 1; $i <= $counter; $i++){
$emails[] = $this->get('email_' . $i);
}
// Now, validate if every email between them are unique
// array_unique() delete repeated values, so we compare
// the size before and after filter the values
$unique = (count($emails) === count(array_unique($emails)));
if (! $unique){
return redirect()->back()
->withMessage('Sorry, all emails should be different');
}
// Now, you need to add every field into the rules
$rules = [];
for ($i = 1; $i <= $counter; $i++){
$rules['email_' . $i] = 'required|email|unique:users,email';
$rules['lastname_' . $i] = 'required';
$rules['firstname_' . $i] = 'required';
$rules['password_' . $i] = 'required';
}
return $rules;
}