# FusionAuth QuickStart for Laravel

Learn how to add FusionAuth login to a PHP Laravel app.

> For the index of this section of the site, see [llms.txt](https://fusionauth.io/docs/llms.txt)

![Laravel](https://fusionauth.io/img/icons/laravel.svg)

This QuickStart explains how to add a login page and authentication to a website built with [Laravel](https://laravel.com/). You'll begin with a simple Laravel app that allows visitors to edit a file. Then, you'll add authentication to the app with a FusionAuth instance. Finally, you'll extend the app to handle multiple independent users with user data provided by FusionAuth.

This tutorial should take between 5 and 15 minutes; less if you already have prerequisites like Docker installed.

## Prerequisites

This QuickStart requires:

*   [PHP](https://www.php.net/manual/en/install.php) 8.3 or later
*   [Composer](https://getcomposer.org/download/) 2 or later
*   [Docker](https://docs.docker.com/get-started/get-docker/) 23 or later

If you use macOS or Windows, you need one of the following container management tools:

*   [Docker Desktop](https://www.docker.com/products/docker-desktop/)
*   [OrbStack](https://docs.orbstack.dev/quick-start) (to use OrbStack for `docker compose` commands after installation, run `docker context use orbstack`)
*   [Podman](https://podman.io/docs/installation) (in the commands below, replace `docker` with `podman`)

## Create a Simple Laravel App

For this QuickStart, we'll use a Laravel app that reads and writes data to a text file:

1.  Create a Laravel project in a folder named `laravel-quickstart`:
    
    ```shell-session
    $ composer create-project laravel/laravel=13.11.0 laravel-quickstart
    ```
    
    Composer installs Laravel, creates a `.env` configuration file, and sets up a SQLite database that Laravel uses to store sessions.
    
2.  Navigate into the project folder:
    
    ```shell-session
    $ cd laravel-quickstart
    ```
    
3.  Replace the contents of `routes/web.php` with the following code:
    
    ```php
    <?php
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\File;
    use Illuminate\Support\Facades\Route;
    
    Route::get('/', function () {
        $path = base_path('note.txt');
    
        return view('notes', ['note' => File::exists($path) ? File::get($path) : '']);
    });
    
    Route::post('/', function (Request $request) {
        File::put(base_path('note.txt'), $request->input('content', ''));
    
        return redirect('/');
    });
    ```
    
    The `GET` route reads the note when the page loads, and the `POST` route saves the note when the form is submitted.
    
4.  In the `resources/views` folder, create a file named `notes.blade.php` with the following code, which displays the note in a form:
    
    ```php
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Notes</h1>
        <form method="post" action="/">
            @csrf
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40">{{ $note }}</textarea><br>
            <button type="submit">Save Changes</button>
        </form>
    </body>
    </html>
    ```
    
    The form includes `@csrf` because Laravel rejects form submissions without a token that prevents [CSRF](https://fusionauth.io/docs/apis/oauth/authorize.md).
    
5.  Run the app:
    
    ```shell-session
    $ php artisan serve --port=3000
    ```
    
6.  Open the app at [http://localhost:3000](http://localhost:3000).
    
7.  Type "Hello Laravel" in the text area, then click Save Changes .
    
8.  In a file browser or terminal, look in the `laravel-quickstart` folder. You should see a new file named `note.txt`, with text content "Hello Laravel".
    
9.  Press **Ctrl+C** on your keyboard to stop the app.
    

## Install and Run FusionAuth

Before we can add authentication to our Laravel app, we need a local FusionAuth instance:

1.  Open your container management tool (listed in the prerequisites above).
    
2.  From the `laravel-quickstart` folder, clone the [GitHub repository for the FusionAuth instance you'll use with this QuickStart](https://github.com/FusionAuth/fusionauth-quickstart-app):
    
    ```shell-session
    $ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git
    ```
    
3.  Navigate into the cloned directory:
    
    ```shell-session
    $ cd fusionauth-quickstart-app
    ```
    
4.  To start a local instance of FusionAuth, run the following command (omit the `-d` flag to see all Docker logs):
    
    ```shell-session
    $ docker compose up -d
    ```
    
5.  Wait until all networks, volumes, and containers show a green status of **Healthy**, **Started**, or **Created**. This may take a few minutes, depending on your network speed and cached dependencies.
    
6.  Open [http://localhost:9011/admin](http://localhost:9011/admin) to access the FusionAuth Admin UI.
    
7.  Log in with these credentials:
    
    *   **Login**: `admin@example.com`
    *   **Password**: `password`
8.  Navigate to Applications . In the QuickStart App row, click Select -> Edit , then click the OAuth tab. On this page, you can find your client Id and client secret, and set redirect and logout URLs. In the next part of this QuickStart, we'll use these values to connect our Laravel app with FusionAuth.
    
9.  Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Laravel app, and because FusionAuth supports SSO, we need to log out of our admin account before we can log in as a normal user.
    

## Add FusionAuth to the Laravel App

Now that you have a working instance of FusionAuth and a working Laravel app, let's use FusionAuth to add login to your Laravel app:

1.  Navigate out of the `fusionauth-quickstart-app` folder, back to the `laravel-quickstart` folder that contains `artisan` and `note.txt`:
    
    ```shell-session
    $ cd ..
    ```
    
2.  Install [Laravel Socialite](https://laravel.com/docs/socialite) and the [FusionAuth provider for Socialite](https://github.com/SocialiteProviders/FusionAuth), which handle communication with our FusionAuth instance:
    
    ```shell-session
    $ composer require laravel/socialite:5.33.0 socialiteproviders/fusionauth:5.0.3
    ```
    
3.  Add the following lines to the end of the `.env` file (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI):
    
    ```plaintext
    FUSIONAUTH_BASE_URL=http://localhost:9011
    FUSIONAUTH_CLIENT_ID=f0510a74-da7a-4101-a474-05e7f1d5ba7e
    FUSIONAUTH_CLIENT_SECRET=super-secret-secret-that-should-be-regenerated-for-production
    FUSIONAUTH_REDIRECT_URI=http://localhost:3000/oauth-callback
    ```
    
4.  In `config/services.php`, add the following entry at the end of the returned array, before the closing `];`. The entry passes the values from `.env` to Socialite:
    
    ```php
    'fusionauth' => [
            'base_url' => env('FUSIONAUTH_BASE_URL'),
            'client_id' => env('FUSIONAUTH_CLIENT_ID'),
            'client_secret' => env('FUSIONAUTH_CLIENT_SECRET'),
            'redirect' => env('FUSIONAUTH_REDIRECT_URI'),
        ],
    ```
    
5.  Replace the contents of `app/Providers/AppServiceProvider.php` with the following code, which adds the FusionAuth provider to Socialite:
    
    ```php
    <?php
    
    namespace App\Providers;
    
    use Illuminate\Support\Facades\Event;
    use Illuminate\Support\ServiceProvider;
    use SocialiteProviders\FusionAuth\Provider;
    use SocialiteProviders\Manager\SocialiteWasCalled;
    
    class AppServiceProvider extends ServiceProvider
    {
        public function boot(): void
        {
            Event::listen(function (SocialiteWasCalled $event) {
                $event->extendSocialite('fusionauth', Provider::class);
            });
        }
    }
    ```
    
6.  Replace the contents of `routes/web.php` with the following code:
    
    ```php
    <?php
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\File;
    use Illuminate\Support\Facades\Route;
    use Laravel\Socialite\Facades\Socialite;
    
    Route::get('/login', function () {
        return view('login');
    });
    
    Route::get('/login/start', function () {
        return Socialite::driver('fusionauth')->enablePKCE()->redirect();
    });
    
    Route::get('/oauth-callback', function (Request $request) {
        $user = Socialite::driver('fusionauth')->enablePKCE()->user();
    
        $request->session()->regenerate();
        $request->session()->put('user', ['id' => $user->getId()]);
    
        return redirect('/');
    });
    
    Route::post('/logout', function (Request $request) {
        $request->session()->invalidate();
    
        return redirect(config('services.fusionauth.base_url').'/oauth2/logout?'.http_build_query([
            'client_id' => config('services.fusionauth.client_id'),
            'post_logout_redirect_uri' => url('/login'),
        ]));
    });
    
    Route::get('/', function (Request $request) {
        if (! $request->session()->has('user')) {
            return redirect('/login');
        }
    
        $path = base_path('note.txt');
    
        return view('notes', ['note' => File::exists($path) ? File::get($path) : '']);
    });
    
    Route::post('/', function (Request $request) {
        if (! $request->session()->has('user')) {
            return redirect('/login');
        }
    
        File::put(base_path('note.txt'), $request->input('content', ''));
    
        return redirect('/');
    });
    ```
    
    The new code connects the app to FusionAuth:
    
    *   The `/login/start` route sends the user to the FusionAuth login page. `enablePKCE()` turns on [PKCE](https://fusionauth.io/docs/authentication/oauth/authorization-code.md#proof-key-for-code-exchange), so a stolen authorization code is useless on its own.
    *   The `/oauth-callback` route receives the authorization code from FusionAuth. Socialite exchanges the code for an access token and uses the token to fetch the user's details from FusionAuth's UserInfo endpoint. The app then stores the user's Id in the Laravel session.
    *   The `/logout` route clears the Laravel session, then sends the user to FusionAuth's `/oauth2/logout` endpoint so the FusionAuth session ends too. FusionAuth then sends the user back to `/login`.
    *   The `/` routes send users who aren't logged in to `/login`.
7.  In the `resources/views` folder, create a file named `login.blade.php` with the following code, which links to `/login/start`:
    
    ```php
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Log in</title>
    </head>
    <body>
        <h1>Log in to Notes</h1>
        <a href="/login/start">Log in with FusionAuth</a>
    </body>
    </html>
    ```
    
8.  Replace the contents of `resources/views/notes.blade.php` with the following code, which adds a Logout button:
    
    ```php
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Notes</h1>
        <form method="post" action="/">
            @csrf
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40">{{ $note }}</textarea><br>
            <button type="submit">Save Changes</button>
        </form>
        <form method="post" action="/logout">
            @csrf
            <button type="submit">Logout</button>
        </form>
    </body>
    </html>
    ```
    
9.  Run the app, which now uses FusionAuth login:
    
    ```shell-session
    $ php artisan serve --port=3000
    ```
    
10.  Open the app at [http://localhost:3000](http://localhost:3000) and click Log in with FusionAuth .
     
11.  Log in with the following credentials:
     
     *   **Login**: `richard@example.com`
     *   **Password**: `password`
12.  Edit and save the note in the authenticated Laravel app.
     
13.  Click Logout . FusionAuth ends your session and sends you back to the login page.
     

## Add Independent Notes for Each User

To see a more realistic example of FusionAuth usage, we can improve the app even more, so every user gets a unique note to edit. To accomplish this, we'll use FusionAuth's user data:

1.  Open the FusionAuth Admin UI at [http://localhost:9011/admin](http://localhost:9011/admin).
    
2.  Log in with the following credentials:
    
    *   **Login**: `admin@example.com`
    *   **Password**: `password`
3.  Navigate to Applications . In the QuickStart App row, click Select -> Edit , then click the Registration tab.
    
    *   Under **Self-service registration**, check that **Registration mode** is set to **Create registration**. The QuickStart configuration has already turned on self-service registration.
    *   In the **Registration field** list, turn on the **Enabled** and **Required** switches for the following rows:
        *   **Birthdate**
        *   **First name**
        *   **Last name**
4.  Click Save in the top right of the page to save your changes to self-service registration.
    
5.  Navigate to Users . In the Richard Hendricks row, click Select -> Manage .
    
6.  In the Source tab, look for the `firstName` and `lastName` fields. That's what we'll use to personalize the UI for each user. We'll use the user's `id` field to generate a unique name for each user's note.
    
7.  Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Laravel app.
    
8.  Replace the contents of `routes/web.php` with the following code, which stores the user's name (first and last) and Id in the session, and stores each user's note in a separate file:
    
    ```php
    <?php
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\File;
    use Illuminate\Support\Facades\Route;
    use Laravel\Socialite\Facades\Socialite;
    
    Route::get('/login', function () {
        return view('login');
    });
    
    Route::get('/login/start', function () {
        return Socialite::driver('fusionauth')->enablePKCE()->redirect();
    });
    
    Route::get('/oauth-callback', function (Request $request) {
        $user = Socialite::driver('fusionauth')->enablePKCE()->user();
    
        $request->session()->regenerate();
        $request->session()->put('user', [
            'id' => $user->getId(),
            'name' => $user->getName() ?: 'writer',
        ]);
    
        return redirect('/');
    });
    
    Route::post('/logout', function (Request $request) {
        $request->session()->invalidate();
    
        return redirect(config('services.fusionauth.base_url').'/oauth2/logout?'.http_build_query([
            'client_id' => config('services.fusionauth.client_id'),
            'post_logout_redirect_uri' => url('/login'),
        ]));
    });
    
    Route::get('/', function (Request $request) {
        $user = $request->session()->get('user');
        if (! $user) {
            return redirect('/login');
        }
    
        $path = base_path("user_data/note-{$user['id']}.txt");
    
        return view('notes', [
            'name' => $user['name'],
            'note' => File::exists($path) ? File::get($path) : "Write a note, {$user['name']}.",
        ]);
    });
    
    Route::post('/', function (Request $request) {
        $user = $request->session()->get('user');
        if (! $user) {
            return redirect('/login');
        }
    
        File::ensureDirectoryExists(base_path('user_data'));
        File::put(base_path("user_data/note-{$user['id']}.txt"), $request->input('content', ''));
    
        return redirect('/');
    });
    ```
    
    The FusionAuth provider requests the `profile` scope by default, so the UserInfo response already includes the user's first and last name. `getName()` returns the full name.
    
9.  Replace the contents of `resources/views/notes.blade.php` with the following code, which greets the user by name:
    
    ```php
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Welcome, {{ $name }}</h1>
        <form method="post" action="/">
            @csrf
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40">{{ $note }}</textarea><br>
            <button type="submit">Save Changes</button>
        </form>
        <form method="post" action="/logout">
            @csrf
            <button type="submit">Logout</button>
        </form>
    </body>
    </html>
    ```
    
10.  Open the app at [http://localhost:3000](http://localhost:3000) and click Log in with FusionAuth . The development server loads the changed files on each request, so you don't need to restart it.
     
11.  Log in with the following credentials:
     
     *   **Login**: `richard@example.com`
     *   **Password**: `password`
12.  In a separate private or incognito window, open the app at [http://localhost:3000](http://localhost:3000) and click Log in with FusionAuth .
     
13.  Click Create an account and create an account using your personal email address, a password, your name, and your birthdate.
     
14.  Edit and save your own note. Your name appears at the top of the page and in the default note text.
     

Your Laravel app now provides unique notes for each user. Each user can independently edit and save their note. When a user saves a note, the app writes the note to a `note-<id>.txt` file in the `user_data` directory. To identify which note belongs to which user, compare the `id` in the file name with the `id` field in the user's Source tab in the Admin UI. Log out of the app before you open the Admin UI. Otherwise, FusionAuth single sign-on logs you in to the Admin UI as the app user, who doesn't have access to the Admin UI.

## Summary

In this QuickStart, FusionAuth handled login for your Laravel app:

*   Socialite sent users to the FusionAuth login page and exchanged the authorization code for tokens, so the app never saw their passwords.
*   The session check in the `/` routes kept logged-out users away from the notes page.
*   FusionAuth gave the app each user's unique Id and name. The app used the Id to keep each note separate and the name to greet the user.
*   FusionAuth's self-service registration let new users create their own accounts, with no sign-up code in the app.

## Next Steps

This was a quick introduction to using FusionAuth for user authentication. To learn more about integrating FusionAuth with your product, see [Get Started](https://fusionauth.io/docs/get-started.md).

FusionAuth has many features (including [Social Login](https://fusionauth.io/docs/authentication/identity-providers.md#social-identity-providers), [Single Sign-On](https://fusionauth.io/docs/authentication/sessions/enable-sso.md), [Passkeys](https://fusionauth.io/docs/authentication/passkeys/configure.md), [Multi-factor Authentication](https://fusionauth.io/docs/authentication/multi-factor-authentication.md)), most of which are free. This example app is a great starting point for learning about FusionAuth features.

Related

[Quickstarts FusionAuth QuickStart for Laravel API QuickStart integration of a Laravel API application using FusionAuth. laravel authentication](https://fusionauth.io/docs/quickstarts/api/quickstart-php-laravel-api.md)

[Quickstarts FusionAuth QuickStart for PHP QuickStart integration of PHP web application with FusionAuth. php web login](https://fusionauth.io/docs/quickstarts/web/quickstart-php-web.md)
---

## Other pages in Web

> For the full index of this section, see [Quickstarts](https://fusionauth.io/docs/llms-quickstarts.txt).

- [FusionAuth QuickStart for Python Django](https://fusionauth.io/docs/quickstarts/web/django.md): Integrate FusionAuth with an example Python Django website.
- [FusionAuth QuickStart for .NET](https://fusionauth.io/docs/quickstarts/web/dotnet.md): Learn how to add FusionAuth login to an ASP.NET Core Razor Pages app.
- [FusionAuth QuickStart for Express](https://fusionauth.io/docs/quickstarts/web/express.md): Integrate FusionAuth with an example Express website.
- [FusionAuth QuickStart for Python Flask](https://fusionauth.io/docs/quickstarts/web/flask.md): Integrate FusionAuth with an example Python Flask website.
- [Web](https://fusionauth.io/docs/quickstarts/web.md): Explore step-by-step web application QuickStart guides from FusionAuth to seamlessly integrate authentication into your application.
- [FusionAuth QuickStart for Next.js](https://fusionauth.io/docs/quickstarts/web/nextjs.md): Integrate FusionAuth with an example Next.js website.
- [FusionAuth QuickStart for Nuxt](https://fusionauth.io/docs/quickstarts/web/nuxt.md): Integrate FusionAuth with an example Nuxt website.
- [FusionAuth QuickStart for Golang](https://fusionauth.io/docs/quickstarts/web/quickstart-golang-web.md): QuickStart integration of a Golang web application with FusionAuth using the CoreOS OIDC library.
- [FusionAuth QuickStart for Remix](https://fusionauth.io/docs/quickstarts/web/quickstart-javascript-remix-web.md): QuickStart integration of Javascript Remix web application with FusionAuth.
- [FusionAuth QuickStart for Drupal](https://fusionauth.io/docs/quickstarts/web/quickstart-php-drupal-web.md): QuickStart integration of Drupal web application with FusionAuth.
- [FusionAuth QuickStart for PHP](https://fusionauth.io/docs/quickstarts/web/quickstart-php-web.md): QuickStart integration of PHP web application with FusionAuth.
- [FusionAuth QuickStart for Rust with Actix](https://fusionauth.io/docs/quickstarts/web/quickstart-rust-actix-web.md): QuickStart integration of a Rust Actix web application with FusionAuth.
- [FusionAuth QuickStart for WordPress](https://fusionauth.io/docs/quickstarts/web/quickstart-wordpress-web.md): QuickStart integration of WordPress application with FusionAuth.
- [FusionAuth QuickStart for Ruby on Rails](https://fusionauth.io/docs/quickstarts/web/rails.md): Integrate FusionAuth with an example Ruby on Rails website.
- [FusionAuth QuickStart for Spring Boot With Thymeleaf](https://fusionauth.io/docs/quickstarts/web/spring-boot.md): Learn how to add FusionAuth login to a Spring Boot app with Thymeleaf.
