> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication introduction

> Learn the basics of Laravel's authentication features—from setting up an authentication system with a starter kit to retrieving the authenticated user.

## What is authentication

Authentication is the mechanism for confirming "who" the user accessing your application is.
In web applications, you receive an email and password via a login form, and if they are correct, save the user's information in the session.
On subsequent requests, that session is used to identify the user.

Laravel's authentication features are built around two concepts: "guards" and "providers."

* **Guards** define how the user is authenticated on each request. The default is the `session` guard, which uses sessions and cookies to manage state.
* **Providers** define how users are retrieved from your database. The default uses Eloquent.

<Info>
  The authentication configuration file is `config/auth.php`. The default configuration works for most web applications as-is.
</Info>

```mermaid theme={null}
flowchart TD
    A["Login request"] --> B["Guard<br>(defines auth method)"]
    B --> C["Provider<br>(fetches user from DB)"]
    C --> D{"Auth check"}
    D -- "Success" --> E["Store user info<br>in the session"]
    E --> F["Redirect to<br>authenticated page"]
    D -- "Failure" --> G["Redirect to<br>login screen"]
```

## Authentication with starter kits

In Laravel, by choosing a starter kit when creating your application with `laravel new`, authentication features like login, registration, and password reset are automatically built for you. This is the most recommended approach.

<Steps>
  <Step title="Create the application">
    Create your application with the Laravel installer. It will prompt you to choose a starter kit during setup.

    ```shell theme={null}
    laravel new my-app
    ```

    You can select **React**, **Vue**, **Livewire**, or **Svelte** as your starter kit.
    Choose one that matches your team's technology stack.
  </Step>

  <Step title="Install frontend dependencies">
    ```shell theme={null}
    cd my-app
    npm install && npm run build
    ```
  </Step>

  <Step title="Prepare the database">
    Verify the database configuration in your `.env` file, then run migrations.

    ```shell theme={null}
    php artisan migrate
    ```

    The initial migrations, including the `users` table, are applied.
  </Step>

  <Step title="Start the development server">
    ```shell theme={null}
    composer run dev
    ```

    Visit `http://localhost:8000` in your browser, and you'll see "Register" and "Log in" links in the navigation.
    Visit `/register` and try registering a user.
  </Step>
</Steps>

Once you have the starter kit, the following features are available right away.

| Feature            | URL                 |
| ------------------ | ------------------- |
| User registration  | `/register`         |
| Login              | `/login`            |
| Password reset     | `/forgot-password`  |
| Email verification | `/email/verify`     |
| Edit profile       | `/settings/profile` |

<Tip>
  All the code generated by the starter kit (controllers, routes, views) lives inside your own application. You can freely modify and customize it.
</Tip>

### Available starter kits

#### React

Build a modern SPA using React 19, TypeScript, Tailwind, and [shadcn/ui](https://ui.shadcn.com).
By using [Inertia](https://inertiajs.com), you can use a React frontend while retaining server-side routing.

#### Vue

Uses Vue Composition API, TypeScript, Tailwind, and [shadcn-vue](https://www.shadcn-vue.com/).
Like React, it uses Inertia to integrate with the server.

#### Livewire

Uses [Livewire](https://livewire.laravel.com) to build dynamic UIs entirely in PHP.
Ideal for teams that primarily work with Blade templates or want to avoid JavaScript frameworks.
Includes the [Flux UI](https://fluxui.dev) component library.

#### Svelte

Uses Svelte 5, TypeScript, Tailwind, and [shadcn-svelte](https://www.shadcn-svelte.com/).
Combines with Inertia to build a modern SPA.

## The Auth facade

Using the `Auth` facade, you can get information about the currently authenticated user and check the authentication state.

### Getting the authenticated user

```php theme={null}
use Illuminate\Support\Facades\Auth;

// Get the current user
$user = Auth::user();

// Get only the user ID
$id = Auth::id();
```

In a controller, you can also get the user from the `Request` object.

```php theme={null}
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();

        return view('dashboard', ['user' => $user]);
    }
}
```

### Checking authentication state

`Auth::check()` returns `true` or `false` depending on whether the user is logged in.

```php theme={null}
use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // Logged in
} else {
    // Not logged in
}
```

In Blade templates, the `@auth` and `@guest` directives are convenient.

```blade theme={null}
@auth
    <p>Hello, {{ Auth::user()->name }}</p>
    <a href="/logout">Log out</a>
@endauth

@guest
    <a href="/login">Log in</a>
    <a href="/register">Register</a>
@endguest
```

## Protecting routes

To create routes that only authenticated users can access, use the `auth` middleware.

```php theme={null}
// routes/web.php

// Accessible only to authenticated users
Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware('auth');
```

An unauthenticated user attempting access is automatically redirected to `/login`.

To protect multiple routes at once, use groups.

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

<Warning>
  Forgetting to add the `auth` middleware allows unauthenticated users to access your routes. Always apply it to routes that require protection.
</Warning>

### Guest-only routes

Use the `guest` middleware to redirect users who are already logged in.
Applying it to login and registration pages redirects already-logged-in users to the dashboard.

```php theme={null}
Route::middleware('guest')->group(function () {
    Route::get('/login', [AuthController::class, 'showLogin']);
    Route::get('/register', [AuthController::class, 'showRegister']);
});
```

## Manual authentication

To implement login manually without using a starter kit, use `Auth::attempt()`.

```php theme={null}
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    public function login(Request $request): RedirectResponse
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        if (Auth::attempt($credentials)) {
            // Authentication succeeded — regenerate the session to prevent CSRF attacks
            $request->session()->regenerate();

            return redirect()->intended('/dashboard');
        }

        // Authentication failed
        return back()->withErrors([
            'email' => 'Email or password is incorrect.',
        ])->onlyInput('email');
    }
}
```

Pass an array of credentials as the first argument to `Auth::attempt()`.
The password is automatically compared against the hash, so pass it in plaintext.

To implement "remember me" functionality, pass `true` as the second argument.

```php theme={null}
// Use the value of the "remember me" checkbox
Auth::attempt($credentials, $request->boolean('remember'));
```

<Info>
  Even when implementing manual authentication, we recommend referring to the starter kit's code. It's a great reference for a secure implementation.
</Info>

## Logout

To log a user out, call `Auth::logout()`.
It's a best practice to also invalidate the session and regenerate the CSRF token.

```php theme={null}
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;

class LogoutController extends Controller
{
    public function logout(Request $request): RedirectResponse
    {
        Auth::logout();

        // Invalidate the session
        $request->session()->invalidate();

        // Regenerate the CSRF token
        $request->session()->regenerateToken();

        return redirect('/');
    }
}
```

Use POST for the route.

```php theme={null}
Route::post('/logout', [LogoutController::class, 'logout'])->middleware('auth');
```

In Blade templates, use a form to send a POST request.

```blade theme={null}
<form method="POST" action="/logout">
    @csrf
    <button type="submit">Log out</button>
</form>
```

## Summary

| What you want to do        | How                                 |
| -------------------------- | ----------------------------------- |
| Add authentication quickly | Starter kit (`laravel new`)         |
| Get the current user       | `Auth::user()` / `$request->user()` |
| Check login state          | `Auth::check()`                     |
| Protect a route            | `->middleware('auth')`              |
| Log in manually            | `Auth::attempt($credentials)`       |
| Log out                    | `Auth::logout()`                    |

## Next steps

<Card title="Middleware" icon="shield-halved" href="/en/middleware">
  Learn about how the `auth` middleware works and how to build your own middleware.
</Card>


## Related topics

- [Starter kits](/en/starter-kits.md)
- [Hashing](/en/hashing.md)
- [Password reset](/en/passwords.md)
- [Email verification](/en/verification.md)
- [Laravel Fortify and Starter Kits](/en/advanced/fortify.md)
