Lekz Flores Lekz Flores - 2 months ago 27x
PHP Question

Laravel 5 Add errors in an array using After Validation Hook

I'm trying to add a function in my app where users are allowed to change their account password. I have three fields and my view looks like this:

<form class="form" role="form" action="{{ url('users/updatePassword') }}" method="post">
{{ csrf_field() }}

<div class="form-group label-floating {{ $errors->has('oldpassword') ? 'has-error' : '' }}">
<label class="control-label" for="oldpassword">Old Password</label>
<input type="password" name="oldpassword" class="form-control">

@if ($errors->has('oldpassword'))
<span class="help-block">
<strong>{{ $errors->first('oldpassword') }}</strong>

<div class="form-group label-floating {{ $errors->has('newpassword') ? 'has-error' : '' }}">
<label class="control-label" for="newpassword">New Password</label>
<input type="password" name="newpassword" class="form-control">

@if ($errors->has('newpassword'))
<span class="help-block">
<strong>{{ $errors->first('newpassword') }}</strong>

<div class="form-group label-floating">
<label class="control-label" for="newpassword_confirmation">Confirm Password</label>
<input type="password" name="newpassword_confirmation" class="form-control">

<div class="form-group">
<button class="btn btn-raised btn-primary">Change</button>

Firstly, I want to check if all fields are completely filled up and for that I used
. And then check if the
is match from the database so I use
if (Auth::attempt(array('password' => $request->oldpassword)))
condition. I also found in the laravel 5.2 documentation the After Validation hook. I don't know what is wrong but it seems it don't validates the
field when I typed a wrong password.

My controller:

$validator = Validator::make($request->all(), [
'oldpassword' => 'required|max:255',
'newpassword' => 'required|min:6|max:255|confirmed',
$validator->after(function($validator) use($request) {
if (Auth::attempt(array('password' => $request->oldpassword))) {
$validator->errors()->add('oldpassword', 'Old password dont match in our database.');
if ($validator->fails()) {
// Toastr
$title = "Oops!";
$message = "Please make sure to fill all required fields.";
$options = [
'progressBar' => false,
'positionClass' => 'toast-top-right',
'timeOut' => 6000,
Toastr::error($message, $title, $options);
return redirect()->back()
} else {
return 'success'; // for testing only

Any idea regarding this?


According to your code when you enter correct oldpassword you get the error. So change if(Auth::attempt..... to if(!Auth:attempt.... And also if you use Auth:attempt you have to logout user again(this method also requires unique field like username or email to identify the user). so it's better if you use following method

if (!\Hash::check($request->get('oldpassword'), \Auth::user()->password)) {
     $validator->errors()->add('oldpassword', 'Old password dont match in our database.');