Home  >  Q&A  >  body text

How to verify that input password matches database hashed password in Laravel 8

<p>How to verify user password from given request in Laravel? How is the password compared to the password hash stored in the database? ** This is my controller **</p> <pre class="brush:php;toolbar:false;"><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class MainController extends Controller { function login1(Request $request){ $username = $request->input('username'); $password = $request->input('password'); $data = DB::table('users')->where(['username'=>$username, 'password'=>$password])->first(); if($data == null){ echo "error"; $notification = array( 'message' => 'User does not exist! ', 'alert-type' => 'error' ); return back()->with($notification); } else{ $request->session()->put('user',$data); return redirect('dashboard'); } }}</pre></p>
P粉129731808P粉129731808441 days ago496

reply all(2)I'll reply

  • P粉373990857

    P粉3739908572023-08-29 00:51:27

    like this

    $encrypted = Crypt::encrypt('password_name_variable');

    reply
    0
  • P粉071559609

    P粉0715596092023-08-29 00:50:53

    Basically, what you want to do is:

    1. Queryusers Users with a given username in the table.
    2. Check if their hashed password matches the hash of the provided password.

    So, you want to first query for users with a given username. Then, after retrieving the user and verifying its existence, you can check if the provided password matches the hashed password on the retrieved model.

    public function login(Request $request): Response
    {
        $user = User::where('username', $request->get('username'));
    
        if (!$user || !Hash::check($request->get('password'), $user->password)) {
            return back()->with([
                'message' => '用户名和/或密码不正确。',
                'alert-type' => 'error'
            ]);
        }
    
        $request->session()->put('user', $user);
    
        return redirect('dashboard');
    }
    

    However, there are built-in functions in Laravel to achieve this, and depending on your needs, it may be simpler to do this:

    public function login(Request $request): Response
    {
      if (!Auth::attempt(['username' => $request->get('username'), 'password' => $request->get('password')]) {
            return back()->with([
                'message' => '用户名和/或密码不正确。',
                'alert-type' => 'error'
            ]);
        }
    
        return redirect('dashboard');
    }

    https://laravel.com/api/8.x/Illuminate/Support/Facades/Auth.html#method_attempt

    reply
    0
  • Cancelreply