Laravel 5.4 add a message to validator's errors - php

So I am receiving data from a form that should reset user passwords:
Old Password: |field|
New Password: |field|
Confirm Password: |field|
And i want to be able to display a message out for the user if his old password does not match what he entered in the first field. I don't want to make an entirely new validation method and just want to throw an error to the use when i make my own if(). So how do I achieve this using the $errors variable that is available in my blade views
So here is an example of my controllers method
public function update(Request $request){
$this->validate($request,[
'oldPassword' => 'required',
'password' => 'required|min:8|confirmed'
]);
$user = Auth::user();
if(password_verify($request->newPass,$user->password)){
$user = User::find($user->id);
$user->password = bcrypt($request->newPass);
$user->save();
}else{
//the code for adding a new key to $errors variable
return back(); Or return redirect('path');
}
}
So in the view I want to this
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

You can do this in your controller:
$validator = Validator::make($request->all(),[
'oldPassword' => 'required',
'password' => 'required|min:8|confirmed'
]);
And then before your return back();, add:
$validator->after(function($validator) {
$validator->errors()->add('tagName', 'Error message');
});
With your message.

Related

Undefined variable for hidden input after registration - Laravel

I have this method of trying to get their email to resend verification link if they didnt receive the first time. The problem is i dont want to let them login without verification because this database is connected with a game server and i dont want them to log in without verification. I tried to store the email so the resend button resends it to that email the verification link but after i register and when its trying to redirect me to the verify.blade i get.
Undefinded variable: user
And its pointing to the hidden input which i will show below.
This is my registration function which works fine and registers the user in the database:
protected function create(array $data)
{
$user = Account::create([
'login' => $data['login'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'verifyToken'=> Str::random(40),
'active' => (env('CONFIRM_EMAIL', true)) ? 0 : 1
]);
$thisUser = Account::findOrFail($user->id);
if(env('CONFIRM_EMAIL') == true){
$this->sendEmail($thisUser);
}
return $user;
}
This is the function that redirects or logins the user depending if i have set to True the email verification:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
if(env('CONFIRM_EMAIL') == false){
$this->guard()->login($user);
}else{
return redirect(route('verifyEmail'));
}
if ($response = $this->registered($request, $user)) {
return $response;
}
return $request->wantsJson()
? new Response('', 201)
: redirect($this->redirectPath());
}
and this is the resend function and html code with the hidden input that points the error to the value="$user->email":
protected function resend(Request $request)
{
$user = Account::where('email', $request->email)->first();
if($user){
$user->verifyToken = Str::random(40);
$user->save();
$this->sendEmail($user);
return back()->with('user',$user)->with('success', 'A link has been sent to your email');
}
}
<form action=" {!! route('resendEmail') !!}" method="POST">
#csrf
<input type="hidden" name="email" value="{{ $user->email }}">
<button class="btn btn-default db" type="submit" value="Submit">Resend Verification Link</button>
</form>
This is the route for verifyemail which i dont know how to pass the email parameter:
return redirect(route('verifyEmail'));

how to handle laravel login errors, username different from password

I'm using Laravel 5.4 and I want to handle failed login errors message. But I want make it a little more custom. I want to show special errors like (username not found) or (password is wrong).
What can I do? (I did it and it's working, check my new failed login method, is this correct and standard?)
Failed login method:
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => trans('auth.failed')];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
in my blade:
#if ($errors->first('phone'))
<ul>
#foreach($errors->all() as $error)
<li>{{ $errors->first('phone') }}</li>
#endforeach
</ul>
#endif
my new failed method:
if (!User::where('phone', $request->phone)->first()){
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors([
$this->username() => 'user not found',
]);
}
if (!User::where('phone', $request->phone)->where('password', bcrypt($request->password))->first()){
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors([
'password' => 'password is incorrect',
]);
}
You could change the default auth validation messages in your resources > lang > en > passwords.php or auth.php files

Issues with validation of signup form

I'm adding a validation to my sign up form , the validate code is working but the errors don't shows up in the page
PHP code
public function postSignUp(Request $request)
{
$this->validate($request, [
'email'=> 'required|email|unique:users',
'first_name'=> 'required|max:120',
'password' => 'required|min:4'
]);
$email = $request['email'];
$first_name = $request['first_name'];
$password = bcrypt($request['password']);
$user = new User();
$user->email = $email;
$user->first_name = $first_name;
$user->password = $password;
$user->save();
Auth::Login($user);
return redirect()->route('dashboard');
}
Welcome.blade.php code
#section('content')
#if(count($errors) > 0)
<div class="row">
<div class="col-md-6">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
</div>
#endif
the php code is working because if i tried to register with an email that already taken it wont register but the error is that errors are not showing up in the welcome page
You are not passing the error messages back to the view.
As stated at documentation
if ($validator->fails())
{
return redirect('dashboard')->withErrors($validator);
}
You are checking with the function count($errors) but that is an object and it will always enter the condition since you are counting the object not the list itself.
Replace #if(count($errors) > 0) with #if(!empty($errors->all()))

laravel validation callback not work

i'm trying to use callback to simply to check my form input, the offical code is here: https://laravel.com/docs/5.2/validation
the following is my function
public function addthread(Request $request) {
$input = $request->all();
$rules = array('title' => 'required|unique:thread|max:255');
$message = array('title.required' => 'The :attribute field is aaa required.');
$validator = Validator::make($input, $rules, $message);
$validator->after(function($validator) {
if ($this->checkOpt()) {
$validator->errors()->add('num_opt', 'Something is wrong with this field!');
echo 'test';
}
});
if ($validator->fails()) {
return redirect('addthreadhtml')->withErrors($validator)->withInput();
}
}
public function checkOpt() {
return false;
}
the blade tpl:
#if (count($errors) > 0)
<div class="container" stytle="max-width:80%">
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
#endif
The num_opt error never print out, any idea?
checkOpt() is returning FALSE, so the code will never enter the if statment.
if ($this->checkOpt()) { // this is returning false, right ?? so, its not adding the error
$validator->errors()->add('num_opt', 'Something is wrong with this field!');
echo 'test';
}
Your checkOpt() always returns false, so your condition won't ever be satisfied.

Validate/Authorize Current Password In Laravel 5.1

I'm trying to add a password change feature for my logged in/authorized users. It's your plain ole generic set up:
Current Password
New Password
Confirm New Password
Obviously I can just use validate on the new password and password confirmation, but how do I authorize the current password submitted against their actual current password?
In the users model password is a hidden property so I can't just match them up.
I tried looking through Illiminate\Auth and Guard but I didn't see it anywhere. Perhaps I missed it, or maybe I'm going about this the wrong way?
Here's the answer in case anyone else is looking:
$validator = $this->validator($request->all());
$validator->after(function($validator) use ($request) {
$check = auth()->validate([
'email' => $this->user->email,
'password' => $request->current_password
]);
if (!$check):
$validator->errors()->add('current_password',
'Your current password is incorrect, please try again.');
endif;
});
if ($validator->fails()):
return redirect('account/password')
->withErrors($validator)
->withInput();
endif;
$this->user->password = bcrypt($request->password);
$this->user->save();
Get the current password and compare with the new password.
//use Auth, Hash, Input;
if (Hash::check(Input::get('new_password'), Auth::user()->password))
echo "Matched";
else
echo "Not matched";
Did you use the the laravel built in authentication package? If yes, the validation has been done for you. Check app/Http/Controller/Auth/AuthController.php, you can see this validation function. You can add more if you wish!:
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
If any error happens during the above validation, it will be sent to the $errors variable where your blade view can catch them. So, in your reset password view (view/auth/reset.blade.php), you can catch the validation errors as follow:
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Categories