问题描述
我正在尝试在单个 axios 调用中验证两种不同类型的数据:Profile 和 ProfileSocial。问题是,当我基于第二个模型创建 ProfileSocialRequest 并尝试对其进行验证时,它返回 Call to a member function validated() on null
;如果我在尝试验证它之前返回数据,它会返回一个有效的对象。
个人资料社交
class ProfileRequest extends FormRequest
{
public function rules()
{
return [
'name' => [
'required','string',],...
'socials' => [
'required','array','min:1',];
}
}
ProfileSocialRequest
use Illuminate\Foundation\Http\FormRequest;
class ProfileSocialRequest extends FormRequest
{
public function rules()
{
return [
'profile_id' => [
'required','integer','social_type_id' => [
'required','handle' => [
'required',];
}
}
配置文件控制器
public function store(ProfileRequest $request)
{
$data = $request->validated(); // this (ProfileRequest) works fine
$sosicalReq = new ProfileSocialRequest($request['socials'][0]); // This returns a valid object: {"social_type_id":1,"handle":"mySocialNetworkHandle","profile_id":1000}
$socialReqData = $sr->validated(); // ERROR: Call to a member function validated() on null
...
}
我的问题是,如果调用validated() 方法的每一步都返回一个完整对象,为什么$socialReq
被读取为null?
解决方法
我不确定您想要实现什么,而是手动创建验证类而不是
$sosicalReq = new ProfileSocialRequest($request['socials'][0]);
你应该使用:
$sosicalReq = app()->make(ProfileSocialRequest::class);
但它会验证整个输入而不仅仅是 $request['socials'][0]