Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Authentication

Authentication is checking who the user is. Laravel has everything ready for it: the User model, the users table and the Auth facade. The Laravel Breeze starter kit provides finished login and registration pages, but it helps to understand how it works inside.

Registration

A password is never stored in plain text — it is hashed with Hash::make():

use App\Models\User;
use Illuminate\Support\Facades\Hash;
 
public function register(Request $request)
{
    $data = $request->validate([
        'name' => 'required|max:255',
        'email' => 'required|email|unique:users',
        'password' => 'required|min:8|confirmed',
    ]);
 
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
 
    Auth::login($user);
 
    return redirect('/profile');
}

Logging in

The Auth::attempt() method finds the user by email and compares the password with the hash:

use Illuminate\Support\Facades\Auth;
 
public function login(Request $request)
{
    $credentials = $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);
 
    if (Auth::attempt($credentials)) {
        $request->session()->regenerate();
 
        return redirect('/profile');
    }
 
    return back()->withErrors(['email' => 'Wrong email or password.']);
}

The current user

$user = Auth::user();    // a User object or null
$id = Auth::id();        // the identifier or null
$loggedIn = Auth::check(); // true if the user is logged in

Templates have directives for this:

@auth
    <p>Hello, {{ auth()->user()->name }}!</p>
@endauth
 
@guest
    <a href="/login">Log in</a>
@endguest

Protecting pages

The auth middleware redirects guests to the login page:

Route::get('/profile', [ProfileController::class, 'show'])->middleware('auth');

Logging out

public function logout(Request $request)
{
    Auth::logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();
 
    return redirect('/');
}

Log out with a POST form, not a link — otherwise a user can be logged out from another site.

Common mistake

After a successful login you must call $request->session()->regenerate(). Without it the session identifier stays the same, and an attacker who planted their own identifier on the victim beforehand gains access to the account. This is called session fixation.

Thanks for reading!

Donate to the site — we work hard for you.