Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 67 ยท Authentication and Authorization

Authentication Overview and Starter Kits

Understand how Laravel authentication works: guards, user providers, the auth config file, starter kits for React, Vue and Livewire, Fortify, and how to choose.

Almost every real application needs to answer two questions: who is making this request? and what are they allowed to do? The first is authentication, the second is authorization. This chapter covers both, and this lesson draws the map: which pieces Laravel gives you, how they fit together, and which starting point to pick for a new project.

Laravel's answer to authentication is deliberately layered. At the bottom sit two small ideas, guards and user providers, that decide how a user is recognized and where user records come from. On top of those, official packages and starter kits give you ready-made registration, login, password reset and profile screens, so you rarely write the boring parts yourself. Knowing the bottom layer makes the top layer easy to customize.

The remaining lessons zoom in on each piece, starting with Registering, Logging In and Out. If sessions are new to you, read Sessions, Flash Data and Cookies first, because the default guard stores its state there.

Guards and providers

Every authentication setup in Laravel is a combination of two things, configured in config/auth.php:

  • A guard defines how users are authenticated for each request. The built-in session guard reads a user id from the session (which the browser keeps alive with a cookie). A token guard, like the one used by Sanctum, looks for a bearer token in the request instead.
  • A user provider defines how users are fetched from storage. The eloquent provider uses an Eloquent model. The database provider uses the query builder directly.

A guard asks its provider two kinds of questions: "give me the user with this id" (used after the session says who you are) and "does this user match these credentials?" (used at login). Splitting the work this way means you can change where users live (another table, an external service) without touching how login works, and add a new way to log in (a token) without touching storage.

flowchart LR
    R["Request"] --> G["Guard<br/>(session or token)"]
    G -->|"find by id / credentials"| P["User provider<br/>(eloquent)"]
    P --> M["User model<br/>(users table)"]
    G --> U["Authenticated user<br/>or guest"]

A guard decides how the request proves who it is; the provider knows where users are stored.

Here is the heart of a fresh Laravel application's config/auth.php, trimmed. It is real Laravel code, so it is read-only here:

PHP
return [
    'defaults' => [
        'guard' => env('AUTH_GUARD', 'web'),
        'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
    ],

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => env('AUTH_MODEL', App\Models\User::class),
        ],
    ],

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_reset_tokens',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],
];

Reading it top to bottom: the default guard is web; that guard uses the session driver and gets its users from the users provider; that provider is Eloquent with your User model; and the password reset settings (we cover them in Fortify, Email Verification and Password Reset) point at the same provider.

The Auth facade

In your own code you rarely touch guards directly. The Auth facade forwards to the default guard:

PHP
use Illuminate\Support\Facades\Auth;

Auth::check();            // true when someone is logged in
Auth::guest();            // the opposite
Auth::user();             // the User model, or null
Auth::id();               // the user's primary key, or null

Auth::guard('admin')->check();   // ask a specific guard instead

Inside a controller you can also read the user from the request, which is easier to test and works with any guard:

PHP
public function show(Request $request): View
{
    return view('profile', ['user' => $request->user()]);
}

In Blade, @auth and @guest show content depending on login state. Routes are protected with the auth middleware, which redirects guests to the login page (or returns a 401 JSON response for API requests); see Middleware.

Most applications use a single guard and never think about the list. You add a second guard when you have a truly different kind of user, such as a separate admin guard with its own table, or when an API authenticates by token while the website uses sessions.

A guard and provider you can run

Laravel itself can't run on this site, but the idea is small enough to rebuild in plain PHP. The stand-in below has the same moving parts: a provider interface, an in-memory provider, a session-backed guard and an AuthManager that builds guards from a config array. Names mirror Laravel's, though the real classes do much more (events, remember-me cookies, hashing through the Hasher contract).

PHP A tiny AuthManager with a session guard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second request never saw the password. It only found a user id in the session and asked the provider for that user, which is exactly how the real session guard behaves between page loads. Notice that AuthManager knows nothing about arrays or passwords: the config picks the provider, and the provider owns storage.

A second guard for a different kind of client

Because the guard and provider are separate, the same users can be recognized in a different way. A token guard doesn't use the session at all; it reads a header. In the next stand-in the two guards share one provider and differ only in how they find the user for a request. This is the shape of what Sanctum does for APIs (API Authentication with Sanctum).

PHP Two guards, one provider

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last line shows why guards matter: the same valid token is worthless on the web guard, because that guard only looks at the session. In Laravel you choose the guard per route, for example auth:web or auth:sanctum.

Starter kits

You could build login, registration, password reset, email verification and a profile page by hand using the pieces above. You almost never should. Laravel ships starter kits: complete, working application skeletons that you generate once and then own. The kit's code is copied into your project (controllers, views or components, routes, tests), so you can read and change every line. There is no hidden framework layer to fight.

When you run laravel new my-app, the installer asks which starter kit you want:

  • React: an Inertia-based front end written in React with TypeScript and Tailwind, with pages and layouts already built.
  • Vue: the same idea with Vue.
  • Livewire: server-driven components in PHP with Blade, with no JavaScript framework to learn (Livewire Basics).
  • None: a plain skeleton. You add authentication yourself or skip it.

The current kits build their backend on Laravel Fortify, described below, so registration, login, password reset, email verification and profile updates arrive wired up and tested. The installer also asks about a test framework (Pest is the default) and, for some kits, optional features such as two-factor authentication. The exact prompts and options change between releases, so treat the installer's own questions as the source of truth (Installing Laravel and Creating a Project walks through them).

Older projects, and many tutorials online, mention Laravel Breeze and Laravel Jetstream. They are the previous generation of starter kits. They still work and you may inherit a project built on one, but a new project should start from the current kits.

Fortify, Sanctum and friends

Several official packages sit behind or beside the kits. Knowing their roles keeps you from installing the wrong one:

Package Role
Fortify A headless authentication backend: it registers the routes and controllers for login, registration, password reset, verification, profile and (optionally) two-factor authentication, and you supply the views.
Sanctum Lightweight API tokens and cookie-based authentication for SPAs.
Passport A full OAuth2 server, for when third parties need to sign in with your accounts.
Socialite "Sign in with GitHub, Google, ..." through OAuth providers.

The next lessons cover them in detail: Fortify in Fortify, Email Verification and Password Reset and Sanctum in API Authentication with Sanctum.

Choosing a starting point

A short decision guide works for most projects:

  • A website with pages you render on the server and a bit of interactivity: pick the Livewire kit, or the "none" option with Blade and Alpine.
  • A rich, app-like front end and your team knows React or Vue: pick that kit. You get Inertia, which lets Laravel controllers return page components without a separate API.
  • A mobile app or a separate front-end calling your JSON API: build the API with Sanctum tokens, and add the web kit only if you also have a website.
  • You need to sign in third-party apps with your own accounts: that's the Passport use case. It's rarer than people think.
  • You are learning: start with the Livewire kit or a plain project, read the generated code, and delete what you don't need.

The choice of front end is covered more in Blade, Livewire, Inertia or an SPA?. Whichever you choose, the guard and provider underneath are the same.

After generating a starter kit, read its routes and controllers before you change anything. It is the fastest way to learn real-world Laravel conventions, and it shows exactly which pieces are Fortify's and which are yours.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a guard decide in Laravel?

    A guard defines how a request proves who it is. Storage is the provider's job, and permissions belong to authorization (gates and policies).
  2. 2. Which part of config/auth.php says that users are loaded through the User Eloquent model?

    Providers describe where users come from. The eloquent driver loads them through the model named in model.
  3. 3. Why can the same API token be rejected by the web guard but accepted by an API guard?

    Guards are the strategy for recognizing a request. A session guard ignores bearer tokens, a token guard ignores the session.
  4. 4. What is true about the code a starter kit generates?

    Starter kits publish controllers, views or components, routes and tests into your application, so there is no hidden layer to override.
  5. 5. Which package is the right one when third-party applications must sign in using your application's accounts via OAuth2?

    Passport is a full OAuth2 server. Socialite is the opposite direction (you sign in through someone else's provider), and Fortify handles your own users' login screens.

Summary

  • Authentication answers "who are you?"; authorization answers "what may you do?". Laravel handles them separately.
  • A guard decides how a request is authenticated (session, token); a user provider decides where users are loaded from (Eloquent, database). Both are configured in config/auth.php.
  • Auth::check(), Auth::user(), $request->user(), @auth and the auth middleware are the everyday tools; use Auth::guard('name') for a non-default guard.
  • Starter kits (React, Vue, Livewire) generate a complete, editable authentication UI on top of Fortify. Breeze and Jetstream are the older generation.
  • Sanctum covers API tokens and SPA cookie auth, Passport is a full OAuth2 server, Socialite signs users in through other providers.
  • Pick the kit that matches your front-end approach; the guard and provider concepts are the same under all of them.

Next: Registering, Logging In and Out