Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

zdrave's avatar

Illuminate\Validation\ValidationException : The given data was invalid.

Hello, I have this problem in file SchoolRequest.php

<?php

namespace App\Http\Requests\School;

use Illuminate\Foundation\Http\FormRequest;

class SchoolRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'school_number' => 'required',
            'school_name' => 'required'
        ];
    }

    /**
     * Translate fields with user friendly name.
     *
     * @return array
     */
    public function attributes()
    {
       return [
            'school_number' => trans('school.school_number'),
            'school_name' => trans('school.school_name')
        ];
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
        ];
    }
}

in repo this

public function findOrFail($id)
    {
        $school = $this->school->find($id);

        if (!$school) {
            throw ValidationException::withMessages(['message' => trans('school.could_not_find')]);
        }

        return $school;
    }

and this is the error

 Illuminate\Validation\ValidationException  : The given data was invalid.

  at F:\ZDRAVE\laravel-vuejs-starter-kit-with-bootstrap4-admin-template\vendor\laravel\framework\src\Illuminate\Foundation\Http\FormRequest.php: 117
  113:      * @throws \Illuminate\Validation\ValidationException
  114:      */
  115:     protected function failedValidation(Validator $validator)
  116:     {
  117:         throw (new ValidationException($validator))
  118:                     ->errorBag($this->errorBag)
  119:                     ->redirectTo($this->getRedirectUrl());
  120:     }
  121:
  122:     /**

  Exception trace:

  1   Illuminate\Foundation\Http\FormRequest::failedValidation(Object(Illuminate\Validation\Validator))
      F:\ZDRAVE\laravel-vuejs-starter-kit-with-bootstrap4-admin-template\vendor\laravel\framework\src\Illuminate\Validation\ValidatesWhenResolvedTrait.php : 26

  2   Illuminate\Foundation\Http\FormRequest::validateResolved()
      F:\ZDRAVE\laravel-vuejs-starter-kit-with-bootstrap4-admin-template\vendor\laravel\framework\src\Illuminate\Foundation\Providers\FormRequestServiceProvider.php : 30

  Please use the argument -v to see more details.

Thanks

0 likes
5 replies
lostdreamer_nl's avatar

ValidationException .....

    public function rules()
    {
        return [
            'school_number' => 'required',
            'school_name' => 'required'
        ];
    }

These FormValidations are used to validate forms (figures). When it throws a validation exception, it's because you are going to that route, but are not POSTing data according to the rules you setup

But where is the route where you are injecting this?

// some SchoolController perhaps ?
public function store(SchoolRequest  $request) 
{
    $school = School::create($request->all());
    return redirect()->back()->withMessage('The school has been created');
}

This is basically how you should use the requests.... on the other side of a POST route, where it validates the data or redirects the user back to the page they came from with a bunch of error messages about missing data.

Also, why the extra boilerplate code?:

public function findOrFail($id)
    {
        $school = $this->school->find($id);

        if (!$school) {
            throw ValidationException::withMessages(['message' => trans('school.could_not_find')]);
        }

        return $school;
    }
// could simply be:
public function findOrFail($id)
{
    return $this->school->findOrFail($id);
}
zdrave's avatar

Still the same error I change like you said but the same error.

 /**
     * Used to store school.
     *
     * @post ("/api/school")
     *
     * @param ({
     *      @Parameter("school_number", type="integer", required="true", description="School Number"),
     *      @Parameter("shool_name", type="string", required="true", description="School Name"),
     * })
     *
     * @return Response
     */
    public function store(SchoolRequest $request)
    {
        $this->authorize('create', School::class);

        $school = $this->repo->create($this->request->all());

        return $this->created(['message' => trans('school.school_added')]);
    }

this is controller

and create method in repository

/**
     * Create a new School.
     *
     * @param array $params
     *
     * @return School
     */
    public function create($params)
    {
        return $this->school->forceCreate($this->formatParams($params));
    }

private method in repository for params

private function formatParams($params)
    {
        $formatted = [
            'school_number' => gv($params, 'school_number'),
            'school_name' => gv($params, 'school_name'),
        ];

        return $formatted;
    }

helper gv

function gv($params, $key, $default = null)
{
    return (isset($params[$key]) && $params[$key]) ? $params[$key] : $default;
}

I hope this clear out things

lostdreamer_nl's avatar

Are you posting both the school_number and school_name fields from a form to this route?

The thing I dont understand is: A ValidationException should normally be caught by the Illuminate Exception Handler:

        if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        } elseif ($e instanceof AuthenticationException) {
            return $this->unauthenticated($request, $e);
        } elseif ($e instanceof ValidationException) {
            return $this->convertValidationExceptionToResponse($e, $request);
        }

"The given data was invalid" is the default message for this exception, but in the response given by the handler, you should be getting more data about which fields did not validate correctly.

Where are you getting this exception trace from?

zdrave's avatar

When I want to see route:list from php artisan route:list this popup and I can not see my routes

lostdreamer_nl's avatar

...... where are you using this 'SchoolRequest' ?? (do a global find through your whole project if you must)

Because THAT shouldn't happen.

I'm thinking you are putting it somewhere directly in your routes file...

Please or to participate in this conversation.