Kritim Yantra
Jun 05, 2025
Authentication is a big deal in web development — it's what keeps your users' data safe and your app secure. Laravel, one of the most popular PHP frameworks, gives you two amazing tools to handle API authentication: Passport and Sanctum.
But which one should you choose for your project? Don’t worry — this guide will help you understand the difference in plain, beginner-friendly language.
Laravel 12 gives developers two powerful options to handle API authentication:
Feature | Passport (OAuth2) | Sanctum (Simple Tokens) |
---|---|---|
Complexity | High | Low |
Use Case | Third-party apps, APIs | SPAs, mobile apps |
Setup Time | Longer | Quick and easy |
Token Types | Access, Refresh, Personal | API tokens, Session cookies |
Best For | Complex apps | Simpler, first-party apps |
Use Passport if your app needs:
Use Sanctum if your app is:
Here’s how you can install and use Passport:
Install the package
composer require laravel/passport
Run migrations
php artisan migrate
Install Passport
php artisan passport:install
Update your User model
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}
Set up API guard in config/auth.php
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Protect your routes
Route::middleware('auth:api')->group(function () {
// Protected routes here
});
Optional: Token expiration settings
use Laravel\Passport\Passport;
Passport::tokensExpireIn(now()->addDays(15));
Passport::refreshTokensExpireIn(now()->addDays(30));
Sanctum is easier and faster to get running. Here’s how to do it:
Install the package
composer require laravel/sanctum
Publish the config file
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Run the migrations
php artisan migrate
Update your User model
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}
Protect your routes
Route::middleware('auth:sanctum')->group(function () {
// Protected routes here
});
Issue tokens
$token = $user->createToken('token-name')->plainTextToken;
Use in API requests
Authorization: Bearer your_token_here
If you're building a frontend with Vue, React, or a mobile app:
.env
:SANCTUM_STATEFUL_DOMAINS=localhost:3000,127.0.0.1:8000
/sanctum/csrf-cookie
before login to enable CSRF protection.Scenario | Recommended Package |
---|---|
Need OAuth2 for third-party apps | Laravel Passport |
Building a first-party SPA or mobile app | Laravel Sanctum |
Want a quick and simple setup | Laravel Sanctum |
Need advanced token control | Laravel Passport |
Developing large-scale enterprise APIs | Laravel Passport |
Both Laravel Passport and Sanctum are excellent tools — it all depends on what your app needs.
Whichever you choose, Laravel makes authentication secure and developer-friendly.
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google