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?
I finally found a solution. Posting it here in case it may help someone.
The problem lies in the
cookie
session driverThe 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 theredis
driver.