Learn Laravel · 8/17

Authentication & Security: Guarding the Gates

7 min read

Hello there, future Laravel legend! 🐧

Welcome to the "Authentication & Security" section. Think of this as learning how to be the bouncer for your application's exclusive VIP club. You'll decide who gets in, what they're allowed to see, and how to keep their information safe and sound. It's a big responsibility, but luckily, Laravel makes it surprisingly straightforward and, dare I say, fun.

Let's get those gates guarded!


1. Scaffolding Auth Fast: Introducing Laravel Breeze 💨

The Problem: Every time you start a new web application, you need a way for users to sign up, log in, and reset their password. Building this from scratch is like re-inventing the wheel for every car you build. It's time-consuming, repetitive, and you might accidentally make the wheel square (which is bad for security).

The Solution: Laravel Breeze is a starter kit that builds all of this for you in minutes. It sets up all the necessary routes, controllers, and views for a complete authentication system. It's like an "Authentication System in a Box"—just add water (or, in this case, a few simple commands).

Getting Started with Breeze (The Practical Bit)

Here is the most common, up-to-date way to get Breeze up and running in a new Laravel project.

Step 1: Install a Fresh Laravel Project

First things first, open your terminal and create a new Laravel application if you haven't already.

bash
composer create-project laravel/laravel my-vip-club
cd my-vip-club

Step 2: Install Laravel Breeze

Next, we'll pull in the Breeze package using Composer, PHP's package manager.

bash
composer require laravel/breeze --dev

Step 3: Run the Breeze Install Command

This is the magic wand. This command will ask you which frontend stack you'd like (we'll stick with the classic "Blade" for now) and then generate all the authentication files for you.

bash
php artisan breeze:install

You'll be prompted to choose your stack. Select Blade. It will then ask about dark mode support and which testing framework you prefer. Feel free to choose what you like.

Step 4: Install Dependencies & Build Assets

Breeze uses Tailwind CSS for styling, which requires some JavaScript packages. Let's install and compile them.

bash
npm install
npm run dev

Step 5: Run Your Database Migrations

Breeze created the necessary database table structures for you (like the users table). Let's tell the database to actually create them. Make sure your .env file is configured with your database credentials first!

bash
php artisan migrate

That's it! Seriously. Start your local server (php artisan serve) and navigate to your application in the browser. You will now see "Log in" and "Register" links in the top-right corner. You have a fully functional authentication system. How cool is that?


2. Protecting Routes with the Auth Middleware 🛡️

The Problem: Okay, users can log in. But right now, anyone—logged in or not—can visit any page. We need a way to block off certain areas, like a user dashboard, so only authenticated users can see them.

The Solution: Meet Middleware. Think of middleware as a series of security checkpoints an HTTP request must pass through before it reaches its destination (your controller). Laravel comes with a built-in auth middleware that does exactly this: it checks if the user is logged in. If they aren't, it redirects them to the login page.

How to Use the auth Middleware

This is something you'll do all the time as a Laravel developer. Open up your routes/web.php file.

Protecting a Single Route:

Let's say you have a route to a user's dashboard. To protect it, you simply chain the middleware() method onto the route definition.

php
use App\Http\Controllers\DashboardController;

// This route can only be accessed by logged-in users.
Route::get('/dashboard', [DashboardController::class, 'index'])->middleware('auth');

If a guest tries to visit /dashboard, they'll be automatically bounced to the /login page. Simple and effective!

Protecting a Group of Routes:

It's very common to have a whole section of your site that's for authenticated users only. Instead of adding the middleware to every single route, you can group them.

php
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\SettingsController;

Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    Route::get('/profile', [ProfileController::class, 'show'])->name('profile');
    Route::get('/settings', [SettingsController::class, 'edit'])->name('settings');
});

Everything inside that group is now guarded by your trusty auth middleware. This is the industry-standard way to organize protected routes.


3. Accessing the Authenticated User Data 🙋

The Problem: A user is logged in and is on their dashboard. Great. But how do we actually get their information to personalize the page, like displaying "Welcome, Jessica!"?

The Solution: Laravel gives you incredibly easy ways to access the currently logged-in user's data from anywhere in your application.

The Two Most Common Ways

There are a few methods, but these two are by far the most popular and what you'll see in 99% of projects.

  1. The auth() Helper Function: This is a global function you can use anywhere. It's short, sweet, and requires no special imports.
  2. The Auth Facade: This provides a static-like interface to the authentication services. It's very readable and "Laravel-y".

Both auth()->user() and Auth::user() will return the user model instance if a user is logged in, or null if they are a guest.

Example in a Controller:

Let's imagine our DashboardController wants to get the user's name and pass it to a view.

php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; // <-- Don't forget to import the Facade!

class DashboardController extends Controller
{
    public function index()
    {
        // Using the Auth facade
        $user = Auth::user();

        // Or using the helper (no import needed)
        // $user = auth()->user();

        // Now you can access properties like name, email, etc.
        $userName = $user->name;

        return view('dashboard', ['name' => $userName]);
    }
}

Example in a Blade View:

You can even access the user's data directly in your Blade templates.

blade
{{-- In your resources/views/dashboard.blade.php file --}}

<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Dashboard') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900">
                    {{-- Access the authenticated user's name directly! --}}
                    Welcome back, {{ auth()->user()->name }}!
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

4. Password Hashing and CSRF Protection (Under the Hood) 🔐

This part is more about appreciating what Laravel does for you automatically. You rarely need to implement this stuff manually, but knowing it's there is like knowing your car has airbags—it's comforting.

Password Hashing

The Problem: You should NEVER, EVER store user passwords as plain text in your database. If your database is ever compromised, the attacker would have everyone's passwords. That's a catastrophe.

The Solution: Password Hashing. This is a one-way process that scrambles a password into a long, unrecognizable string. When a user tries to log in, you hash the password they entered and compare it to the hash in the database. You never "un-hash" anything.

Laravel handles this automatically for you. When a user registers through the Breeze scaffolding, Laravel uses the Hash facade with a strong algorithm called Bcrypt.

Here's a peek at what it looks like under the hood (you won't have to write this code when using Breeze):

php
use Illuminate\Support\Facades\Hash;

// When creating a user
$user->password = Hash::make('my-secret-password-123');

// When checking a password during login
if (Hash::check('my-secret-password-123', $user->password)) {
    // The passwords match...
}

A fun fact: Bcrypt is designed to be slow on purpose! This makes it much harder for attackers to run through billions of potential passwords to try and find a match (a "brute-force" attack).

Cross-Site Request Forgery (CSRF) Protection

The Problem: Imagine you are logged into your bank's website. You then visit a malicious website, which has a hidden form that automatically submits a request to your bank's website to transfer money. Since you are already logged in, your browser happily sends your session cookie along with the request, and the bank thinks you made it. This is a Cross-Site Request Forgery attack.

The Solution: CSRF Tokens. Laravel generates a unique, secret token for every user session. Every form in your application must include this token. When the form is submitted, Laravel checks that the token from the form matches the one in the session. If they don't match, the request is rejected. The malicious website has no way of knowing what the user's secret token is, so its fake form will fail validation.

How to use it? You barely have to think about it! Breeze already does this for you. Just add the @csrf Blade directive inside any <form> tag.

blade
<form method="POST" action="/profile">
    @csrf  {{-- This little guy is your hero --}}
    ...
</form>

This directive generates a hidden input field containing the secret token, and the VerifyCsrfToken middleware (which is enabled by default for all web routes) handles the rest.


Extra Reading 📚

Challenge

You are building a secure user dashboard for a Laravel application. Your task is to ensure that only authenticated users can access the dashboard and its related settings page. You also need to fetch the authenticated user's data within the controller to personalize the dashboard welcome message.

Your Tasks:

  1. In the web.php file, create a route group that applies the auth middleware to protect a set of routes.
  2. Inside this group, define two routes:
    • A GET route for /dashboard that maps to the index method of the DashboardController.
    • A GET route for /dashboard/settings that maps to the settings method of the DashboardController.
  3. In the index method of the DashboardController, use the global auth() helper function to retrieve the currently logged-in user's instance.
  4. Return a view named dashboard.index from the index method, passing the user's data to it with the key currentUser.

Expected result

Your final code should correctly implement a middleware group in routes/web.php and fetch user data in the DashboardController.

routes/web.php

The routes file should contain a group with the auth middleware applied, enclosing the two required routes.

php
// routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DashboardController;

Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::get('/dashboard/settings', [DashboardController::class, 'settings']);
});

app/Http/Controllers/DashboardController.php

The index method should use the auth()->user() helper to get the user model and pass it to the view in an associative array.

php
// app/Http/Controllers/DashboardController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index()
    {
        $loggedInUser = auth()->user();
        return view('dashboard.index', ['currentUser' => $loggedInUser]);
    }

    public function settings()
    {
        return view('dashboard.settings');
    }
}
php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.