Complete Guide to User Authentication in Laravel 12 | Web and API Authentication
This blog guides you through setting up user authentication in Laravel 12, using both web-based and API authentication methods.
Introduction
Laravel 12 provides excellent tools for setting up user authentication. In this guide, we'll explore how to set up **authentication** for both **web-based** and **API-based** applications using Laravel's built-in tools like **Laravel UI**, **Jetstream**, and **Sanctum**.
Step 1: Install and Set Up Laravel
To begin, create a new Laravel project using the following command:
composer create-project --prefer-dist laravel/laravel laravel-auth-app
Then navigate to your project directory:
cd laravel-auth-app
This will set up a fresh Laravel 12 project for you.
Step 2: Installing Authentication Scaffolding
Laravel 12 doesn't include authentication scaffolding by default. You can install **Laravel UI** or **Jetstream** for this. Below, we explain both options:
Option 1: Laravel UI
Install **Laravel UI** to get simple authentication views such as login and registration:
composer require laravel/ui
php artisan ui bootstrap --auth
npm install && npm run dev
php artisan migrate
This will set up authentication routes and views with **Bootstrap** styling.
Option 2: Laravel Jetstream
If you want advanced authentication features like two-factor authentication, use **Jetstream**:
composer require laravel/jetstream
php artisan jetstream:install livewire
npm install && npm run dev
php artisan migrate
Jetstream adds additional features like session management, API tokens, and more.
Step 3: Configuring Authentication Routes
After installing authentication scaffolding, Laravel automatically generates routes in **routes/web.php**. You’ll find routes for login, registration, and password resets. Example:
Auth::routes();
These routes are protected by middleware to ensure only authenticated users can access certain pages.
Step 4: User Authentication in API
For **API** authentication, Laravel provides **Sanctum**. To set up API authentication:
Install Sanctum:
composer require laravel/sanctum
Publish Configuration and Migrate:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
Set Up Middleware:
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
Define API Routes:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
This route is protected by **Sanctum** middleware, ensuring only authenticated users can access it.
Conclusion
Laravel 12 provides great tools for **user authentication**, whether for a traditional web app or a modern API-based application. In this guide, we've learned how to set up authentication with both **Laravel UI** and **Jetstream**, as well as how to implement **API authentication** with **Sanctum**.