Back to Homepage
Tuesday 13 August 2024
47

How Laravel Hash Passwords

Laravel provides a secure and straightforward way to hash passwords, ensuring that they are stored safely in your database. Password hashing is crucial for protecting user data, as it prevents plain-text passwords from being exposed in case of a database breach. Laravel uses the bcrypt hashing algorithm by default, but it also supports other algorithms like argon2.

Hashing a Password in Laravel

To hash a password in Laravel, follow these steps:

1. Use the Hash Facade: Laravel's Hash facade provides an easy way to hash passwords.

use Illuminate\Support\Facades\Hash;

   $hashedPassword = Hash::make('password123');

2. Storing the Hashed Password: When creating a new user, you should hash the password before saving it to the database:

$user = new User;
   $user->name = 'John Doe';
   $user->email = 'johndoe@example.com';
   $user->password = Hash::make('password123');
   $user->save();

3. Verifying a Password: To verify a user's password during login, use the Hash::check method:

if (Hash::check('password123', $user->password)) {
       // Password is correct
   } else {
       // Password is incorrect
   }

Examples of Password Hashing in Laravel

  • Registering a New User:
public function register(Request $request)
  {
      $validatedData = $request->validate([
          'name' => 'required|string|max:255',
          'email' => 'required|string|email|max:255|unique:users',
          'password' => 'required|string|min:8|confirmed',
      ]);

      $user = User::create([
          'name' => $validatedData['name'],
          'email' => $validatedData['email'],
          'password' => Hash::make($validatedData['password']),
      ]);

      // Additional logic for after registration
  }
  • Changing a Password:
public function changePassword(Request $request)
  {
      $request->validate([
          'current_password' => 'required',
          'new_password' => 'required|string|min:8|confirmed',
      ]);

      $user = Auth::user();

      if (Hash::check($request->current_password, $user->password)) {
          $user->password = Hash::make($request->new_password);
          $user->save();

          // Password changed successfully
      } else {
          // Current password does not match
      }
  }

Official References

Share:
Created by:
Author photo

Jorge García

Fullstack developer