How to verify that input password matches database hashed password in Laravel 8
P粉129731808
P粉129731808 2023-08-28 14:25:49
0
2
451
<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粉129731808
P粉129731808

reply all(2)
P粉373990857

like this

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

P粉071559609

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!