Introduction
Laravel Sanctum provides a featherweight authentication system for SPAs and mobile applications. In this article we'll explore how to set it up professionally.
Installation
First, install Sanctum via Composer:
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
Setup
In your User model, add the trait:
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
Creating Tokens
After login, issue the user a token:
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json(['token' => $token]);
Protecting Routes
Route::middleware('auth:sanctum')->group(function () {
Route::get('/profile', [ProfileController::class, 'show']);
});
Conclusion
Laravel Sanctum is the ideal choice for building APIs for modern apps. Simple, secure, and easy to integrate with Flutter and React Native.