Laravel Sanctum - SPA & API Authentication
Sanctum provides lightweight API token authentication for SPAs, mobile apps, and simple APIs. For SPAs, it uses cookie-based session auth. For mobile/third-party APIs, it issues API tokens. It's simpler than OAuth2 (Passport) and perfect for most applications.
Sanctum Token Auth
# Install Sanctum
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
// User model - add HasApiTokens
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
}
// Issue token on login
public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['Invalid credentials.'],
]);
}
$token = $user->createToken('api-token')->plainTextToken;
return response()->json(['token' => $token, 'user' => $user]);
}
// Protect API routes
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', fn (Request $request) => $request->user());
Route::apiResource('posts', PostController::class);
});
// Client sends: Authorization: Bearer <token>Industry Best Practices
- Always write tests for this functionality - it's the most reliable way to catch regressions when you refactor or update packages
- Document your implementation decisions in code comments, especially when you deviate from Laravel conventions - future team members (including yourself) will thank you
- Follow the single responsibility principle: each class does one thing. If a method grows beyond 20 lines, consider extracting helper methods or moving logic to a service class
- Profile performance with Laravel Debugbar (composer require barryvdh/laravel-debugbar) during development - it shows query counts, memory usage, and timeline for every request
- Keep dependencies up to date: run composer audit regularly to check for security vulnerabilities in your package dependencies
Industry Best Practices
- Always write tests for this functionality - it's the most reliable way to catch regressions when you refactor or update packages
- Document your implementation decisions in code comments, especially when you deviate from Laravel conventions - future team members (including yourself) will thank you
- Follow the single responsibility principle: each class does one thing. If a method grows beyond 20 lines, consider extracting helper methods or moving logic to a service class
- Profile performance with Laravel Debugbar (composer require barryvdh/laravel-debugbar) during development - it shows query counts, memory usage, and timeline for every request
- Keep dependencies up to date: run composer audit regularly to check for security vulnerabilities in your package dependencies
Industry Best Practices
- Always write tests for this functionality - it's the most reliable way to catch regressions when you refactor or update packages
- Document your implementation decisions in code comments, especially when you deviate from Laravel conventions - future team members (including yourself) will thank you
- Follow the single responsibility principle: each class does one thing. If a method grows beyond 20 lines, consider extracting helper methods or moving logic to a service class
- Profile performance with Laravel Debugbar (composer require barryvdh/laravel-debugbar) during development - it shows query counts, memory usage, and timeline for every request
- Keep dependencies up to date: run composer audit regularly to check for security vulnerabilities in your package dependencies
Tip
Tip
Practice Laravel Sanctum SPA API Authentication in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Transform Eloquent models to JSON. Hide sensitive fields.
Practice Task
Note
Practice Task - (1) Write a working example of Laravel Sanctum SPA API Authentication from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Laravel Sanctum SPA API Authentication is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready laravel code.
Key Takeaways
- Sanctum provides lightweight API token authentication for SPAs, mobile apps, and simple APIs.
- Always write tests for this functionality - it's the most reliable way to catch regressions when you refactor or update packages
- Document your implementation decisions in code comments, especially when you deviate from Laravel conventions - future team members (including yourself) will thank you
- Follow the single responsibility principle: each class does one thing. If a method grows beyond 20 lines, consider extracting helper methods or moving logic to a service class