Answer the question
In order to leave comments, you need to log in
Is it possible to reuse a Validator instance?
Validators can be created using the Validator facade. For example, from the documentation:
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
// что-то выполняем
}
$message = $this->ask(‘You message:’);
$validator = Validator::make([
‘message’ => $message,
], [
‘message’ => [‘required|max:200’],
]);
while (true){
if ($validator->fails()) {
//show errors
} else {
// do something
}
$message = $this->ask(‘You message:’);
$validator->setData([‘message’ => $message]);
}
Answer the question
In order to leave comments, you need to log in
So, this question was asked because of the behavior of the validator. It was necessary to understand what is the reason for the one-time use of an instance (instance) of Validator.
As I expected, the reason was banal - a bug.
A fix has been proposed https://github.com/laravel/framework/issues/28288. Not understood at first, but later realized and included as a fix at the suggestion of another developer https://github.com/laravel/framework/commit/0e52e4...
At the moment, there are no restrictions on the reuse of the Validator instance (instance) and no side effects.
And don't forget to update your Laravel version)
Validator::make just creates a new instance.
PS1: In general, it is considered good practice to use contracts https://github.com/illuminate/contracts/blob/maste... via DI, and facades only in the most extreme cases (never).
PS2: In the particular case of validation, it is desirable to use form requests, not controllers.
The validator may have other props, which may change after the ->fails() call. This is a mutable object, so I wouldn't mess around with such bullshit, but would create a new validator instance (or correct my code so that such issues would not arise).
method:
public function show($slug)
{
$blog = Blog::where('slug', $slug)->firstOrFail();
$category = Category::find($blog->category_id);
return view('blog.show', compact('blog'));
}
@foreach ($blogs as $blog)
<a href="{{ route('blog.show', $blog->slug) }}">{{ $blog->title }}</a>
@endforeach
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question