Introduction
Laravel Sanctum is a lightweight package for API token authentication. If you are building a Vue, React, or mobile app that needs to log in to a Laravel backend, Sanctum makes it simple.
In this guide, you will learn how to:
Build registration and login APIs;
Generate access tokens
Protect routes with authentication;
Delete the token on logout
Requirements: PHP 8.2+, Composer, and basic Laravel knowledge.
Step 1: Create a Laravel Project
bash composer create-project laravel/laravel sanctum-auth cd sanctum-auth
Enter fullscreen mode
Exit fullscreen mode
Step 2: Install Sanctum
In Laravel 11 and 12, one command sets up API scaffolding:
bash php artisan install:api
Enter fullscreen mode
Exit fullscreen mode
This installs Sanctum, creates routes/api.php, and publishes the personal access tokens migration.
Configure your database in .env (SQLite or MySQL), then run:
bash php artisan migrate
Enter fullscreen mode
Exit fullscreen mode
Step 3: Add the Trait to the User Model
Open…