How to Switch from Session-Based Authentication to Token-Based Authentication in Laravel 11 with Sanctum?

Updated: Feb 12, 2025

How to Switch from Session-Based Authentication to Token-Based Authentication in Laravel 11 with Sanctum?

To switch from session-based authentication to token-based authentication in Laravel 11 using Sanctum, follow the steps below:

  1. Install Sanctum: If you haven't installed Sanctum yet, you can install it via composer by running the following command in your terminal:
composer require laravel/sanctum
  1. Register Sanctum: After installing Sanctum, you need to register it in your app/Providers/AppServiceProvider.php file by adding the following line in the boot() method:
use Laravel\Sanctum\Sanctum;

if (app()->environment('production')) {
    Sanctum::encrypt(config('sanctum.key'));
}
  1. Update your authentication guard: You need to update your authentication guard to use token-based authentication. Open your config/auth.php file and update the guards array as follows:
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'sanctum',
    ],
],
  1. Create an API route: Create a new route for your API in routes/api.php:
Route::middleware('api')->group(function () {
    // Your API routes go here
});
  1. Update your middleware: Update your middleware to use the api guard:
use App\Http\Middleware\AuthenticateApiToken;

Route::middleware([
    'auth:api',
])->group(function () {
    // Your protected routes go here
});
  1. Generate a new API key: You can generate a new API key for testing purposes by running the following command in your terminal:
php artisan make:auth api --api

This command will generate a new ApiController and api.auth middleware. You can update the ApiController to return a JSON response instead of the default view response.

  1. Update your database schema: You may need to update your database schema to add the api_token column to your users table. You can do this by running the following migration:
php artisan migrate
  1. Test your API: You can test your API by sending a request to one of your protected routes using a tool like Postman or cURL. Make sure to include the Authorization header with a Bearer token:
curl -H "Authorization: Bearer {token}" http://localhost/api/protected

Replace {token} with a valid API token generated for a user. If everything is set up correctly, you should receive a JSON response with the protected data.