我有2个FormRequest
个类(ReadersFormRequest
,SocialMediaFormRequest
),我想存储和更新Reader
。 Reader
可能有0个或多个社交媒体帐户,因此有必要验证请求。
ReadersFormRequest
class ReadersFormRequest extends FormRequest
{
public function rules()
{
return [
'first_name'=>'required',
'last_name'=>'required',
'birthday'=>'required',
'region'=>'required',
'photo_url'=>'required',
'support'=>'required',
'riwayas_id'=>'required',
'description'=>'required',
];
}
}
SocialMediaFormRequest
public function rules()
{
return [
'url'=>'required|url',
'title'=>'required'
];
}
所以我想合并SocialMediaFormRequest
规则
ReadersFormRequest
规则
我找到了解决方案:
SocialMediaFormRequest
public static function rules()
{
return [
'url'=>'required|url',
'title'=>'required'
];
}
ReadersFormRequest
public function rules()
{
return array_merge(SocialMediaFormRequest::rules(),[
'first_name'=>'required',
'last_name'=>'required',
'birthday'=>'required',
'region'=>'required',
'photo_url'=>'required',
'support'=>'required',
'riwayas_id'=>'required',
'description'=>'required',
]);
}
我认为合并已正确完成,但在更新控制器中,当我调用此ReadersFormRequest
时,我不知道会发生什么。
public function update(ReadersFormRequest $request, Readers $reader)
{
// valid and update reader
Readers::whereId($reader->id)->update([
'first_name' => $request->validated()['first_name'],
'last_name' => $request->validated()['last_name'],
'photo_url' => $request->validated()['photo_url'],
'birthday' => $request->validated()['birthday'],
'region' => $request->validated()['region'],
'support' => $request->validated()['support'],
'riwayas_id' => $request->validated()['riwayas_id'],
'description' => $request->validated()['description']
]);
// For update their social media account links
foreach ($request->validated()['url'] as $key => $url)
{
}
return redirect(route('readers.show',$reader));
}
当我输入阅读器表格时,不会调用此控制器。
答案 0 :(得分:0)
改变你的课程:
class ReadersFormRequest extends FormRequest
{
public function rules()
{
return [
'first_name'=>'required',
'last_name'=>'required',
'birthday'=>'required',
'region'=>'required',
'photo_url'=>'required',
'support'=>'required',
'riwayas_id'=>'required',
'description'=>'required',
'url'=>'required|url',
'title'=>'required'
];
}
}
或者如果你真的想要使用一个类:
class ReadersFormRequest extends FormRequest
{
public function rules(SocialMediaFormRequest $social)
{
$mediaRules = $social->rules();
$rules = [
'first_name'=>'required',
'last_name'=>'required',
'birthday'=>'required',
'region'=>'required',
'photo_url'=>'required',
'support'=>'required',
'riwayas_id'=>'required',
'description'=>'required',
];
return array_merge($rules,$mediaRules);
}
}
答案 1 :(得分:0)
这是我在类似情况下的处理方式:
public static function combineValidations($rules1, $rules2)
{
if(!is_array($rules2)) return $rules1;
foreach($rules2 as $key => $item)
{
if(!isset($rules1[$key]))
{
$rules1[$key] = $item;
}else
{
$rules1[$key] .= '|'.$item;
}
}
return $rules1;
}