1

I am not able to display the validation errors on a specific form/page when using $request->validate($rules);. Here is the controller code:

public function store(Request $request) {

  $rules = [
    'dummy-field' => 'required|string',
  ];

  $params = $request->validate($rules);
  // $this->validate($request, $rules); // Same result with this

  dd($params);
}

In my view:

@if($errors->any())
  <div class="alert alert-danger">
    @foreach($errors->all() as $error)
      <div>{{ $error }}</div>
    @endforeach
  </div>
@endif

When I submit the form (without the dummy-field) I'm properly redirected back to the previous page (If my form would pass the validation I should see the dd output), but the error messages are not displayed. I also tried dd($errors) and the ErrorBag is actually empty.

The weird thing is, using a manual Validator the error messages are properly displayed. Refactoring the controller to:

$rules = [
  'dummy-field' => 'required|string',
];

$validator = Validator::make($request->all(), $rules);

if ($validator->fails()) {
  return redirect()->back()->withErrors($validator);
}

dd($validator);

I see the error messages.

I really can't understand this behaviour. I'm using $request->validate() for other forms in my app and I don't have any trouble.

I'm using laravel 8.

Does someone have any idea why something like this could happen?

3
  • check if your session has validation errors after you go to view page Commented Jan 26, 2021 at 19:19
  • No, there is nothing in the session. I only have them when using Validator::make Commented Jan 26, 2021 at 20:24
  • validate() is a helper function provided by laravel you can check it from Commented Jan 27, 2021 at 5:26

1 Answer 1

1

I finally found a solution. Posting it here in case it may help someone.

The problem lies in the cookie session driver

The browser has a maximum size for a cookie (around 4k I think, but it may vary). When using $request->validate(), the redirect will put into the session both the errors and the input. If the input is long enough (in my case I had some textarea with ~300 characters text), the cookie will exceed the maximum size and the browser will ignore it, so Laravel will not be able to retrieve the errors from the session.

I can't use the file driver because my application is distributed across multiple servers beyond a load balancer, so I resolved everything using the redis driver.

Sign up to request clarification or add additional context in comments.

1 Comment

No way. I tried this solution and in my case don't help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.