What you need

  • Computer and internet: a laptop or desktop and a stable connection
  • System: Windows 10 or 11, macOS or Linux
  • Tools: PHP 8.3 or newer, Composer, Git and a code editor (the Laravel installation guide lists the official one-command installer)
  • Before this: Your first Laravel route

Download only from each tool's official site and check the address before installing.

What you will learn

You will learn how websites store passwords so that even the people who run the site cannot read them, why that matters, and how to do it correctly in Laravel. You will also see the mistakes that still cause real data leaks today.

Before this lesson, finish Your first Laravel route. You do not need any security background.

Your folder for this lesson: ~/ewoi-learning/laravel-app, the Laravel project from that lesson. You add one small PHP script and one test file, then commit them. The finished files are in the step folder on GitHub.

Ewoi

This is one of the most important lessons on the site. One careless line here can put thousands of people at risk.

The problem: databases leak

Assume that one day, someone who should not have it will get a copy of your database. It happens to large companies and tiny projects alike: a stolen backup, a misconfigured server, a leaked secret, a bug.

Now picture what they find in the users table. If passwords are stored as plain text, they can read every one. Worse, most people reuse passwords, so the attacker now tries those same emails and passwords on email accounts, banks and social media. Your leak becomes your users' emergency.

The goal of this lesson: even with a full copy of your database, nobody can read your users' passwords.

Three ways to store a password

Method What is stored for kenya2026 If the database leaks
Plain text kenya2026 Every password is readable instantly
Encryption Scrambled text that a key can unscramble Anyone who also finds the key reads them all
Slow hashing A one-way fingerprint that cannot be turned back Attackers must guess, one slow guess at a time

Passwords need the third one. Let us see why.

Hashing vs encryption

These two words get mixed up constantly, so slowly:

  • Encryption is two-way. You lock data with a key and can unlock it later with the key. Perfect for data you need to read again, such as a message or a file.
  • Hashing is one-way. It turns any input into a fixed-length fingerprint. The same input always gives the same fingerprint, but there is no key and no way back.

A smoothie is a good picture. Mango and banana always blend into the same smoothie, but nobody can turn the smoothie back into a mango and a banana.

You never need to read a password again. You only need to check whether the password someone types now matches the one they chose. So you store the fingerprint, and at sign-in you fingerprint what they typed and compare. Same fingerprint, same password.

Ask your AI assistant

Explain the difference between hashing and encryption to a complete beginner, with one everyday example of each. Then ask me two questions to check I understood, and correct my answers.

Why "slow" matters

Attackers who steal hashes do not reverse them; they guess. They take a list of common passwords (123456, password, names plus years), hash each guess, and compare. This is a brute-force attack, and modern graphics cards can try billions of guesses per second against a fast hash.

That is why general-purpose fast hashes such as MD5 or SHA-256 are wrong for passwords, even though they are fine for other jobs. Password hashing functions are deliberately slow: a sign-in takes a fraction of a second, which no user notices, but an attacker's billions of guesses become a trickle.

Salt: why two users with the same password look different

If two users both choose kenya2026, a plain hash would give them the same fingerprint. Attackers could also use giant pre-computed tables of common passwords and their hashes.

A salt fixes both: a random value mixed into each password before hashing, different for every user. Same password, completely different stored hashes, and the pre-computed tables become useless. Good password functions add the salt for you and store it inside the result, so you never handle it yourself.

The right tools: Argon2id and bcrypt

The OWASP Password Storage Cheat Sheet, one of the most widely used security references, recommends:

Function Notes
Argon2id First choice. Slow and needs memory for each guess, which makes attacks with graphics cards expensive. OWASP's minimum: 19 MiB of memory, 2 passes, 1 thread. Laravel's defaults (64 MiB, 4 passes, 1 thread) are above that
bcrypt Long-proven and still acceptable, mainly for existing systems, with a cost factor of at least 10. It reads only the first 72 bytes of a password and ignores the rest

Both handle salting automatically. Laravel supports both.

That 72-byte limit matters for long passphrases: two passwords that share their first 72 bytes count as the same password. With bcrypt, OWASP says to cap passwords at 72 bytes; Laravel can refuse longer ones instead of cutting them silently if you set BCRYPT_LIMIT=72 in .env. Argon2id has no such limit, which is one more reason it is the first choice for new apps.

How Laravel does it

Good news: a new Laravel project already does this correctly. It uses bcrypt by default with a cost of 12 (the BCRYPT_ROUNDS=12 line in your .env file), and the User model hashes passwords automatically. The full settings live inside Laravel itself; you only see a config/hashing.php file in your project if you publish it with php artisan config:publish hashing.

The two functions you need:

use Illuminate\Support\Facades\Hash;

$stored = Hash::make('correct-horse-battery-staple');

Hash::check('correct-horse-battery-staple', $stored); // true
Hash::check('wrong-guess', $stored);                  // false

Hash::make creates the hash. Hash::check takes what someone typed and the stored hash, and tells you whether they match. You never compare hashes yourself with ==: every hash has its own salt, so a fresh hash of the right password never equals the stored one. Hash::check reads the salt and cost from the stored hash, repeats the work and compares safely.

Step 1: see it in plain PHP

Laravel's Hash is built on three functions that come with PHP. Seeing them on their own makes the idea concrete.

Open your terminal and go to your project:

cd ~/ewoi-learning/laravel-app
mkdir -p scripts

mkdir -p scripts makes a scripts folder for small practice files. Create scripts/hash-demo.php in your code editor with this content:

<?php

declare(strict_types=1);

$password = 'kenya2026';

$first = password_hash($password, PASSWORD_DEFAULT);
$second = password_hash($password, PASSWORD_DEFAULT);

echo 'First hash:  '.$first."\n";
echo 'Second hash: '.$second."\n";
echo 'Same text? '.($first === $second ? 'yes' : 'no')."\n";
echo 'Right password matches the first: '.(password_verify($password, $first) ? 'yes' : 'no')."\n";
echo 'Right password matches the second: '.(password_verify($password, $second) ? 'yes' : 'no')."\n";
echo 'Wrong password matches: '.(password_verify('kenya2025', $first) ? 'yes' : 'no')."\n";

$old = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
echo 'Old cost-10 hash needs an upgrade: '.(password_needs_rehash($old, PASSWORD_BCRYPT, ['cost' => 12]) ? 'yes' : 'no')."\n";
Function What it does
password_hash($password, PASSWORD_DEFAULT) Makes a salted, slow hash. PASSWORD_DEFAULT is bcrypt today; PHP may switch it to a stronger function in future
password_verify($typed, $hash) Checks a typed password against a stored hash and returns true or false
password_needs_rehash($hash, ...) Says whether a stored hash was made with older settings and should be replaced at the next sign-in

Run it:

php scripts/hash-demo.php

Expected output (your hashes will be different, which is the point):

First hash:  $2y$12$e1AiBlJ3fRNFFYgVcXvb6uV1pLwMcrFsDhQ735DH46XveXzFRmVMe
Second hash: $2y$12$z5Uj00Bs5W0.82YZWS.qOO6YlZCvSDIIdN9DyrAYZGs7PmaY3Ft32
Same text? no
Right password matches the first: yes
Right password matches the second: yes
Wrong password matches: no
Old cost-10 hash needs an upgrade: yes

If your hashes start with $2y$10$ instead of $2y$12$, your PHP is older than 8.4, where the default cost was 10; that still works, and Laravel sets 12 itself.

Step 2: try it in Laravel

Still in ~/ewoi-learning/laravel-app, open Tinker, Laravel's interactive PHP console:

php artisan tinker

Then type, one line at a time:

$a = Hash::make('kenya2026');
$b = Hash::make('kenya2026');
$a === $b;
Hash::check('kenya2026', $a);
Hash::check('kenya2026', $b);

Tinker prints each result after an = sign: the two hashes, then false, true, true. Look at $a and $b: they start with $2y$12$, which says "bcrypt, cost 12", followed by 22 characters of salt and then the hash. They are different because each has its own salt, so $a === $b is false, yet both checks return true. That is salting working exactly as described. Type exit to leave.

Ewoi

Run Hash::make on the same password a few more times. A new hash every time, and every one still checks out. That surprises everyone the first time.

The "hashed" cast: make mistakes impossible

Open app/Models/User.php in a new Laravel project and you will find, in its casts:

'password' => 'hashed',

This tells Laravel: whenever a password is set on a user, hash it before saving. So this is safe:

$user->password = $request->input('password');
$user->save();

The plain password never reaches the database, even if a developer forgets to call Hash::make. Keep this cast on every model that stores a password.

Step 3: a test that proves it

A test turns "I checked once" into "it is checked every time". Create the test file:

php artisan make:test PasswordHashingTest

This creates tests/Feature/PasswordHashingTest.php. Replace its content with:

<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;

class PasswordHashingTest extends TestCase
{
    use RefreshDatabase;

    public function test_the_database_stores_a_hash_not_the_password(): void
    {
        $user = User::factory()->create(['password' => 'correct-horse-battery-staple']);

        $stored = DB::table('users')->where('id', $user->id)->value('password');

        $this->assertNotSame('correct-horse-battery-staple', $stored);
        $this->assertStringStartsWith('$2y$', $stored);
        $this->assertTrue(Hash::check('correct-horse-battery-staple', $stored));
        $this->assertFalse(Hash::check('wrong-guess', $stored));
    }

    public function test_the_same_password_gives_a_different_hash_each_time(): void
    {
        $first = Hash::make('kenya2026');
        $second = Hash::make('kenya2026');

        $this->assertNotSame($first, $second);
        $this->assertTrue(Hash::check('kenya2026', $first));
        $this->assertTrue(Hash::check('kenya2026', $second));
    }

    public function test_the_hashed_cast_hashes_a_plain_password_on_save(): void
    {
        $user = User::factory()->create();

        $user->password = 'a-new-long-passphrase';
        $user->save();

        $stored = DB::table('users')->where('id', $user->id)->value('password');

        $this->assertNotSame('a-new-long-passphrase', $stored);
        $this->assertTrue(Hash::check('a-new-long-passphrase', $stored));
    }
}
Part What it does
RefreshDatabase Gives every test a fresh, empty test database, so tests never touch your real data
User::factory()->create([...]) Makes a test user; the hashed cast hashes the password on the way in
DB::table('users')->...->value('password') Reads the raw stored value, exactly what a leaked database would show
assert... lines Each one must be true, or the test fails and tells you which line

Run only this test:

php artisan test --filter=PasswordHashingTest

Expected output: three ticks under PASS Tests\Feature\PasswordHashingTest and Tests: 3 passed. Tests run with BCRYPT_ROUNDS=4 (set in phpunit.xml) so they stay fast; your real app still uses 12. If a test fails, read the line it names: a stored value equal to the plain password means the hashed cast was removed from app/Models/User.php.

Now save your work. If this folder is not a Git repository yet, run git init first.

git add scripts/hash-demo.php tests/Feature/PasswordHashingTest.php
git commit -m "Add password hashing demo and tests"
Ewoi

That test is your safety net. If anyone ever removes the hashed cast, the test goes red before a single real password is stored in plain text.

Upgrading later

If you raise the cost, existing users still have hashes made with the old cost. Laravel handles this: when a user signs in successfully, it checks whether their hash uses the current settings (the same job as password_needs_rehash in Step 1) and quietly re-hashes it if not. This is the rehash_on_login setting, on by default.

Switching to Argon2id takes one more step. Set this in your .env file:

HASH_DRIVER=argon2id
HASH_VERIFY=false

HASH_DRIVER chooses Argon2id for every new hash. HASH_VERIFY=false is needed while old bcrypt hashes still exist: by default Hash::check refuses a hash made with a different function, which would stop every existing user from signing in. As users sign in, their hashes are upgraded to Argon2id.

Before you change itTest sign-in on a copy of your app first, and make sure your server's PHP was built with Argon2 support (run php -r "var_dump(defined('PASSWORD_ARGON2ID'));" and look for bool(true)). Hashing settings affect every sign-in.

Hashing is one layer, not the whole wall

Strong hashing protects passwords after a leak. Protect the front door too:

  • Rate limiting: allow only a few sign-in attempts per minute, so online guessing is too slow to work.
  • Password rules: length beats complexity. The current US NIST guidance (SP 800-63B, revision 4) asks for at least 15 characters when a password is the only sign-in step and at least 8 when a second step is also required, allowing at least 64; a check against known leaked and common passwords; no forced mixes such as "one symbol and one capital"; and no forced changes every few months, only when there is a sign of a leak. Laravel's Password::min(15)->uncompromised() rule covers length and the leak check. uncompromised() asks a public database of leaked passwords, sending only the first five characters of the password's SHA-1 fingerprint, never the password.
  • Two-step sign-in: a second step, such as a code from an authenticator app, stops attackers even when they know the password.
  • Never log or email passwords, not even in error messages.

Mistakes that still happen

Problem Cause Fix
One leak exposes every account Passwords stored in plain text Hash with Hash::make or the hashed cast
Whoever finds the key reads every password Passwords encrypted instead of hashed Hash them; encryption is for data you must read back
Billions of guesses per second after a leak MD5 or SHA-256 used for passwords Argon2id or bcrypt through Laravel's Hash
Subtle bugs nobody notices Home-made hashing code Use the framework's functions
The right password never matches Hashing the typed password again and comparing with == (every hash has a new salt) Hash::check($typed, $stored)
Passwords in plain text in log files Logging the whole request body on sign-in Never log password fields
Every user locked out after switching to Argon2id Old bcrypt hashes refused by the algorithm check HASH_VERIFY=false while old hashes remain

Ask your AI assistant

Review this Laravel code that saves and checks user passwords for security problems: [paste your code]. Explain each problem in simple words, why it matters, and the safe Laravel way to do it. Do not change anything else.

Recap

  • Assume your database will leak one day, and plan for it.
  • Passwords are hashed (one-way), never stored in plain text and never encrypted.
  • Use a slow password hash: Argon2id first, bcrypt with a high enough cost also fine. Never MD5 or SHA-256.
  • Salts make identical passwords look different; good functions add them for you.
  • In plain PHP: password_hash, password_verify, password_needs_rehash. In Laravel: Hash::make, Hash::check, and the hashed cast on the model.
  • A test that reads the raw stored value keeps it that way.
  • Add rate limiting, length rules and two-step sign-in around it.

Your practice task

  1. In Tinker, create a user with a password (User::factory()->create(['password' => 'kenya2026'])), then look at the stored value with DB::table('users')->latest('id')->value('password'). Confirm it starts with $2y$.
  2. Use Hash::check to confirm the right password passes and a wrong one fails.
  3. Write three sentences in your notes explaining to a friend why a site should never be able to email you your old password.

Ask your AI assistant

I am learning Laravel 13 and wrote this test to prove passwords are hashed: [paste your PasswordHashingTest]. Without rewriting it for me, tell me one more case worth testing and give me a hint about how to write it.

Check your understanding

1. Why are passwords hashed instead of encrypted?

The site never needs to read the password, only to check it. A one-way hash removes the risk of a stolen key unlocking every password.

2. Two users have the same password. With bcrypt, their stored hashes are...

The salt makes every hash unique, which defeats pre-computed tables and hides which users share a password.

3. Which of these is a good choice for hashing passwords?

MD5 and SHA-256 are built to be fast, which helps attackers guess. Argon2id and bcrypt are slow on purpose.

4. In Laravel, how should you check a password someone typed at sign-in?

Hash::check does the comparison safely, using the salt and settings stored inside the hash.

Get the code on GitHub

Found this useful?

Every lesson stays free. Tap the thumbs up so we know what works, or say thanks with a soda or a coffee: it pays for hosting and new lessons.

Buy me a sodaBuy me a coffee

Want more on this?

Tell us which part was not clear, ask for a follow-up lesson, or request a lesson on any topic. We read every request.

I would like
Only to tell you when it is ready.

WhatsApp

Join the channelChat with us

Free lessons and updates in the channel. Questions about learning or training? Chat with us.