Search code examples
phpmysqlilaravel-5.3bcrypt

How to authenticate email and password with laravel 5.3 manually?


Hello Everyone My question is how can we authenticate our email and password in laravel 5.3 ? I am not using Auth here , I am trying to create login system manually
This is user register method
public function post_register(Request $request){ $this->validate($request , [ 'username' => 'required|' , 'email' => 'required|email|unique:registers' , 'password' => 'required|min:6', 'cp' => 'required|same:password']); $data = new Register; $data->username = $request->username; $data->email = $request->email; $data->password = bcrypt($request->password); $data->save(); return Redirect::back()->with('success' , 'user registred'); }

This is login method

public function post_login(Request $request){
    $this->validate($request , [
        'email' => 'required|email' ,
        'password' => 'required']);

 $data = Register::where('email' , $request->email)->exists();
 if($data){
     Session::put('email' , $request->email);
     return Redirect::to('profile');

 }
 else{
    return Redirect::to('login');

 }

this code is working , but problem is that if i enter registered email and unregistered password then it redirect to profile page. i am not able to authenticate user with email and password because i am using bcrypt() hash function in password and when i try to match http request with stored password , it show error Please help me ,Thanks


Solution

  • It wont work because you are comparing the string results of the hash which isnt correct.

    Changes you Register Function

    $data->password = Hash::make($request->password);
    

    Change Your Login function

    public function post_login(Request $request){
        $this->validate($request , [
            'email' => 'required|email' ,
            'password' => 'required']);
    
        $data = Register::where('email' , $request->email)->first();
        if($data){ 
            if(Hash::check($request->password, $data->password)){
                Session::put('email' , $request->email);
                return Redirect::to('profile');
            }
        }
        return Redirect::to('login');
    }
    

    Explanation

    These changes allow you to use Laravel's built in Hashing functionality for Generating Hashes At Registration & Calculating if a hash is valid during login.