1

I'm trying to validate two different types of data in a single axios call: Profile and ProfileSocial. The problem is, when I create a ProfileSocialRequest based on the second model and try to validate it, it returns Call to a member function validated() on null; if I return the data before attempting to validate it, it returns a valid object.


ProfileSocial

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',
                'integer',
            ],
            'handle' => [
                'required',
                'string',
            ],
        ];
    }
}

ProfileController


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
    ...
}

My question is, why is $socialReq being read as null when calling validated() if every step of the way it returns a complete object?

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
brunouno
  • 595
  • 7
  • 23

1 Answers1

4

I'm not sure what you want to achieve, to but to manually create validation class instead of

$sosicalReq = new ProfileSocialRequest($request['socials'][0]); 

you should use:

$sosicalReq = app()->make(ProfileSocialRequest::class);

but it will validate the whole input not just $request['socials'][0]

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • Ok, so I'm trying to run each of my `social` objects through the validation set on my `ProfileSocialRequest`. My logic was: validate the `ProfileRequest`, then run a loop through the `socials` array and validate each as a `ProfileSocialRequest`. In the question, I only use the first object though. @marcin-nabiałek – brunouno Jan 03 '21 at 17:34
  • 1
    @brunouno You should then use array validation instead https://laravel.com/docs/master/validation#validating-arrays and to it in single request class – Marcin Nabiałek Jan 03 '21 at 17:37