Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

Laravel does not display validation errors when using $request->validate

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?

question from:https://stackoverflow.com/questions/65905616/laravel-does-not-display-validation-errors-when-using-request-validate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...