Laravel/React - 在 Controller 中创建不同的 FormRequest 时“调用成员函数validated() on null”

问题描述

我正在尝试在单个 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]

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...