Laravel 8 - Pass validation errors back to frontend - php

I am using Laravel Framework 8.62.0.
I am validating a form the following way:
$validator = Validator::make($request->all(), [
'title_field' => 'required|min:3|max:100',
'comment_textarea' => 'max:800',
'front_image' => 'required|mimes:jpg,jpeg,png,bmp,tif',
'back_image' => 'required|mimes:jpg,jpeg,png,bmp,tif',
'price' => "required|numeric|gt:0",
'sticker_numb' => "required|numeric|gt:0",
'terms-checkbox' => "accepted",
]);
if ($validator->fails()) {
// Ooops.. something went wrong
return Redirect::back()->withInput();//->withErrors($this->messageBag);
}
I want to display errors in the frontend the following way:
#if ($errors->any())
<div class="alert alert-danger alert-dismissable margin5">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Errors:</strong> Please check below for errors
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
However, my $error variable is emtpy, when validation errors exist, so the validation errors do not get shown in my frontend.
Any suggestions what I am doing wrong?
I appreciate your replies!

You should pass the $validator to withErrors like:
if ($validator->fails()) {
// Ooops.. something went wrong
return Redirect::back()->withErrors($validator)->withInput();
}

That's because your not passing errors.
Try this:
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}

As the previous speakers said, you must of course return the errors. but you can also use the Request Validate Helper. it does this automatically.
$request->validate([...])
As soon as an error occurs, it returns a response with the errors.
https://laravel.com/docs/8.x/validation#quick-writing-the-validation-logic

Related

Validate() message is not working in laravel

my validation is working correctly. but didn't show any message. I mention the below.
in controller
$fields = collect([
'monthly_fees',
'admission',
'due_advance',
'session_fee',
'library',
'sports',
'poor_funds',
'fine',
'reciept',
'milad',
'scout',
'development',
'registration',
'f_tutorial',
's_tutorial',
't_tutorial',
'f_exam',
's_exam',
't_exam',
'labratory',
'transport',
'syllabus',
'certificate',
'testimonial',
'generator',
'extra'
]);
$rules = $fields->mapWithKeys(function ($field) use ($fields) {
return [
$field => 'required_without_all:' . $fields->reject(function ($item) use ($field) {
return $item == $field;
})->implode(',')
];
})->toArray();
$this->validate($request, $rules);
in views
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul class="text-center">
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
I also use these lines of codes in the controller but didn't work.
if($this->validate()->fails()) {
return redirect()->back()->with('error','Please Input minimum 1 field...');
}
I want to do minimum 1 field is required. I have 26 input fields. I always use these codes for single use. but this time want to validate minimum One field required. These codes validate the required but didn't show any messages though I mentioned the errors in blade. can you please help me with these errors? thanks in advance.
I solved my problems. here i used $this->vatidate(...);
it was wrong for me. then I used Validator package and returns a custom message with redirect if fails. then it works.

laravel error messages not display after first redirection

If the incoming request parameters do not pass the given validation rules, I redirect the user back to the previous page.
Even though validation error messages exist in session, they aren't displayed after first redirect.
When i refresh page again the error message are displayed.
Blade
#if ($errors->any())
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
Controller
public function index()
{
$this->validation();
$perpage = request()->input('perpage',10);
$perpage = $perpage<10 ? 10 : $perpage;
$musics = Music::where('title','like','%'.request()->input('title').'%')->paginate($perpage);
$page = request()->input('page',1);
$page_count = intval(ceil($musics->total()/$perpage));
if($page < 1 || (!empty($page_count) && $page > $page_count)){
return redirect(request()->fullUrlWithQuery(['page' => 1]));
}
return view('admin.musics.index',
[
'musics'=>$musics,
'perpage'=>$perpage,
'page'=>$page,
'page_count'=>$page_count
]);
}
private function validation()
{
$validator = Validator::make(request()->all(), [
'title' => 'nullable|max:255',
'page' => 'numeric|min:1',
'perpage' => 'numeric|min:10|in:10,20,30,50,100,200,300,500,1000'
]);
if ($validator->fails()) {
return back()
->withErrors($validator)
->withInput();
}
}
for example, in first image,as you see parameter perpage that should be one of the numbers 10,20,30,50,100,200,300,500,1000 is 22, so error happens, error message exist in session but it isn't displayed!
In second image, I correct the parameter perpage and refresh page, now error is displayed!
I realized that redirect did not work.
When validation fails, redirection doesn't work!
Why it happens?
my route rules is :
Route::namespace('Admin')->prefix('admin')->group(function(){
Route::get('musics','MusicsController#index');
});
I changed return back() to return redirect()->back() and return Redirection::back() , but it doesn't work!
What's the problem?
The point is I use one page (I mean it's not like insert action that I have two method, create method and store method, I don't want to submit form to middle page and then return).
try
return Redirect::back()
->withErrors($validator)
->withInput();

validate() function redirect in chrome browser not showing any validation errors (more than 3 errors)

Laravel 5.4 version
The validate() function works until I test more than 3 errors in the form. Upon automatic redirect after buildfailedvalidationresponse function, the 4 $error messages aren't present on and neither is the old form data. This only doesn't work in chrome. Firefox/internet explorer is fine. I have data dumped throughout the process of validatesrequest file and it shows the $error variables being passed correctly to the buildfailedvalidationresponse function but no errors/old form data are presented after redirect. I was just wondering if anybody has had an issue like this with different browsers.
validation method
protected function validateRegistration(Request $request) {
$rules = array(
'name' => 'required|string',
'email' => array('required','string','email','unique:users,email'),
'phone' => 'required|digits:10',
'userid' => array('required','string','min:6','max:10','unique:users,userid','regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/'),
'password' => array('required','string','min:8','max:12','regex:/^(?
=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/'),
'repeatedpassword' => 'required|string|same:password',
'code' => 'required|digits:4|exists:codes,code'
);
$this->validate($request, $rules);
if ($this) {
$store = new User();
return $store->insertuser();
}
}
blade validation display errors statement
<div class="container">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li> {{ $error }} </li>
#endforeach
</ul>
</div>
#endif
</div>

Form post if password input is current password in Laravel 5.2

I am trying to check if entered password is currently logged in users password and give error message if not.
I have profile editing form with name, email etc.
Last input in form is password input.
How can I check if password that is entered is current password?
In EditProfileRequest i tried (custom request file, made with artisan):
public function rules() {
return [
'first_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users,email,'.Auth::user()->id,
'country_code' => 'digits_between:1,4|numeric',
'phone' => 'digits_between:5,12|numeric',
'password' => 'required|confirmed',
];
}
but it rejected form with correct password.
Then I tried adding to controller this part:
if (!Hash::check(Input::get('password'), Auth::user()->password)) {
return Redirect::back()->withInputs();
}
this worked but I don't get any errors for user and I don't know how to add custom error messages, since I am using built-in validator.
You can pass the custom error message as following.
$validator = Validator::make(Input::all(), $rules);
//Here you are checking your inputs with the validation rules that you are created.
if ($validator->fails())
{
//If the validation fails, check for the password validation too and return the error.
if (!Hash::check(Input::get('password'), Auth::user()->password)) {
return Redirect::back()
->withInputs()
->withErrors(['login' => 'Your custom Error Msg'])
->withErrors($validator);
}
else{
return Redirect::back()
->withInputs()
->withErrors(['login' => 'Your custom Error Msg']);
}
}
As a short answer for your question to get a custom error message:
return Redirect::back()->withInputs()->withErrors(['login'=>'custom msg']);
Also make sure you display the errors in your login page.
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
You can check displaying validation errors on this page https://laravel.com/docs/5.2/validation#quick-displaying-the-validation-errors

withX() does not work in Laravel 4.2

The problem is that withErrors() is working perfectly in this code, but withMessage() isn't.
I also tried with('message', 'Test message!'). In views file, I can retrieve withErrors using $errors variable, but if I want to retrieve withMessage, I have to use Session::get('message'). Why is $message not working?
Controller:
public function registration() {
$rules = array(...);
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()) {
return Redirect::route('registration')->withErrors($validator);
}
else {
//Some code here...
return Redirect::route('registration')->withMessage('Test message!');
}
}
Template:
#extends('default.base')
#section('main')
#if(!empty($errors->all()))
<div class="alert alert-danger" role="alert">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}
#endforeach
</ul>
</div>
#endif
#if(isset($message))
{{ $message }}
#endif
#stop
That is because errors is a special case. When creating a view, Laravel check's if there is a session variable with the name errors. If so it will then pass the contents as $errors to the view.
Illuminate\View\ViewServiceProvider#registerSessionBinder
if ($me->sessionHasErrors($app))
{
$errors = $app['session.store']->get('errors');
$app['view']->share('errors', $errors);
}
This means you either use Session::has('message') and Session::get('message') in your view or you add a View Composer that does basically the same that Laravel does with errors:
View::composer('*', function($view){
if(Session::has('message')){
$view->with('message', Session::get('message'));
}
});

Categories