Home > Software engineering >  Laravel validation couldn't store value after validate and give error 500
Laravel validation couldn't store value after validate and give error 500

Time:11-08

I have a form that using ajax for update data client. In that form there is an input file. Everything is going fine except for updating the file. File is sent, it changed on storage too, but it gives error on validation and didn't change data on database. Here is the code on the controller :

public function update(Request $request, Client $client)
    {
        $validatedData = Validator::make($request->all(), [
            'name' => 'required|max:255',
            'logo'=> 'image|file|max:100',
            'level' => 'required|max:1' 
        ]);

        $validatedData['user_id'] = auth()->user()->id;
        
        if ($validatedData->fails()){
            return response()->json($validatedData->errors());
        } else {

            if($request->file('logo')){
                if($request->oldLogo){
                    Storage::delete($request->oldLogo);
                }
                $validatedData['logo'] = $request->file('logo')->store('logo-clients');
            }
            $validateFix = $validatedData->validate();
            
            Client::where('id', $client->id)->update($validateFix);

            return response()->json([
                'success' => 'Success!'
            ]);
        } 
    }

It gives error on line :

$validatedData['logo'] = $request->file('logo')->store('logo-clients');

With message : "Cannot use object of type Illuminate\Validation\Validator as array"

I use the same code that works on another case, the difference is the other not using ajax or I didn't use Validator::make on file input. I guess it's just wrong syntax but I don't really know where and what it is.

CodePudding user response:

To retrieve the validated input of a Validator, use the validated() function like so:

$validated = $validator->validated();

Docs:

CodePudding user response:

$validatedData is an object of type Illuminate\Validation\Validator.

I would say the error is earlier there as well as this line should give an error also: $validatedData['user_id'] = auth()->user()->id;

As ericmp said, you first need to retrieve the validateddata to an array and then work with it.

  • Related