Laravel Sanctum provides a simple and secure authentication system for APIs and single-page applications (SPAs). It enables token-based authentication while supporting session-based authentication for web applications.
Sanctum was introduced to simplify API authentication and address the complexities of using OAuth for smaller-scale applications.
Install Sanctum:
composer require laravel/sanctum
Publish the configuration:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Protect API routes:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Issue a token for a user:
$token = $user->createToken('API Token')->plainTextToken;
Laravel Sanctum simplifies secure authentication, making it versatile for modern web applications.