0

I have custom validation rule in Laravel that is supposed to check if password that user writes in form matches that password in database in order for him to succefully log in, and if it doesn't match then to display error under password input. Currently when wrong password is entered it just redirect me back to login page and no error is shown. Everything else works perfect. Any help is appreciated. Here is my code.

LoginController.php

public function login(Request $request)
{
    $rules = [
        'email'    => 'required|email|exists:App\User,email', 
        'password' => 'required|alphaNum|min:5,new PasswordValidationRule()'
    ];

    $validator = Validator::make($request->all(), $rules);

    if ($validator->fails()) {
        $request->session()->put('data', $request->input());
        return redirect()->route('login')
            ->withErrors($validator->errors())
            ->withInput($request->session()->put('data', $request->input()));
    } else {
        $userData = array(
            'email'     => $request->get('email'),
            'password'  => $request->get('password')
        );
    }
    
    if (Auth::attempt($userData)) {
        return redirect()->intended('dashboard');
    } else {        
        return redirect()->route('login');
    }
}

PasswordValidationRule.php

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use App\User;
use Illuminate\Support\Facades\Hash;

class PasswordValidationRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $user = User::where('email', $request->email)->first();

        if(Hash::check($value, $user->password)) {
            return true;
        }
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ':attribute Password is incorrect!';
    }
}

login.blade.php

<div class="login-page">
    <div class="login-box">
        <div class="card mb-0">
            <div class="card-body login-card-body">
                <p class="login-box-msg font-weight-bold">Sign in to start your session</p>
                <form method="POST" class="mb-4" action="{{route('login') }}">
                    @csrf
                    <div class="input-group mb-3">
                        <input id="email" type="email" placeholder="Email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}"  autocomplete="email" autofocus>
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <span class="fas fa-user"></span>
                            </div>
                        </div>
                        @error('email')
                        <span class="invalid-feedback" role="alert">
                            <strong>{{ $message }}</strong>
                        </span>
                        @enderror
                    </div>
                    <div class="input-group mb-3">
                        <input id="password" type="password" placeholder="Password" class="form-control @error('password') is-invalid @enderror" name="password"  autocomplete="current-password">
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <span class="fas fa-eye-slash cursor-pointer" style="display: none" onclick="showPassword()"></span>
                                <span class="fas fa-eye cursor-pointer" onclick="showPassword()"></span>
                            </div>
                        </div>
                        @error('password')
                        <span class="invalid-feedback" role="alert">
                            <strong>{{ $message }}</strong>
                        </span>
                        @enderror
                    </div>
                    <div class="float-right">
                        <button type="submit" class="btn btn-primary btn-block font-weight-bold">Sign In</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
3
  • you are using auth::attempt and also validating the password in validation rule, why two times doing the same thing? Commented Aug 7, 2020 at 17:08
  • @Anil Well, if I comment out password in validation rule, it is still the same error Commented Aug 7, 2020 at 17:10
  • because you are not passing anything with the redirect ... look at the if else at the bottom, there is nothing being passed with the response (the else) ... but this isn't a good idea in the first place as i mentioned previously Commented Aug 7, 2020 at 17:17

1 Answer 1

1

You can do something like this, if you have commented out password in validation rule,

if (Auth::attempt($userData)) {
        return redirect()->intended('dashboard');
    } else {        
        return redirect()->route('login')
        ->withErrors(['error'=>'Incorrect username or password']);
        ->withInput($request->session()->put('data', $request->input()));
    }

You can retrieve it using sessions

{{session('errors')->first('error');}}
Sign up to request clarification or add additional context in comments.

4 Comments

if it got that far it passed validation so there won't be any validation errors
I copied this instead of mine, and commented out password in $rules variable and everything is the same. login, logout, mail validation works but password doesn't. when I enter wrong password it just redirects me to login.
I wrote if @rose has commented out the password rule in validation, auth is checked twice
@rose I have edited the answer to use associative array, is it working ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.