Lesson 36 of 50
Laravel Sanctum is a Laravel package used to authenticate users for APIs and single-page applications.
Sanctum commonly supports two authentication approaches:
Sanctum is useful for:
In this lesson, we will learn the basic token-based authentication workflow.
For supported modern Laravel versions, you can use the following command to install API scaffolding, including Sanctum:
php artisan install:api
In existing projects or versions where this command is unavailable, install Sanctum using Composer:
composer require laravel/sanctum
Follow the installation instructions for your Laravel version to publish any required configuration or migration files.
Run migrations when required:
php artisan migrate
Sanctum's personal access tokens are stored in the
personal_access_tokens table.
To create personal access tokens, the authenticatable
model must use Sanctum's
HasApiTokens trait.
Open app/Models/User.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
}
The HasApiTokens trait provides methods
such as createToken() for issuing API tokens.
Keep your existing model configuration and add the trait rather than replacing unrelated project settings.
The login endpoint verifies the user's credentials. If they are correct, it creates a token and returns it to the client.
Create a controller:
php artisan make:controller Api/AuthController
Example controller code:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class AuthController extends Controller
{
public function login(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required', 'string'],
]);
$user = User::where(
'email',
$credentials['email']
)->first();
if (
!$user ||
!Hash::check(
$credentials['password'],
$user->password
)
) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
$token = $user->createToken('mobile-app')->plainTextToken;
return response()->json([
'message' => 'Login successful',
'token' => $token,
'user' => [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
],
]);
}
}
This example assumes users have already been registered and their passwords are stored as secure hashes.
Open routes/api.php and define the
login route and a protected profile route.
use App\Http\Controllers\Api\AuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::post('/login', [
AuthController::class,
'login'
]);
Route::middleware('auth:sanctum')->get(
'/profile',
function (Request $request) {
return response()->json([
'user' => $request->user(),
]);
}
);
Example endpoints:
POST /api/login
GET /api/profile
The login endpoint is public. The profile endpoint requires a valid authenticated request.
In modern Laravel projects, API routing may need to be
enabled or installed first. Follow the setup steps for
your Laravel version if routes/api.php
does not exist.
After login, the client receives a token. For subsequent requests, send it in the Authorization header.
Authorization: Bearer YOUR_API_TOKEN
Accept: application/json
Example request using JavaScript:
fetch('/api/profile', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer YOUR_API_TOKEN'
}
})
.then(response => {
if (!response.ok) {
throw new Error('Request failed: ' + response.status);
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
Replace YOUR_API_TOKEN with the token
returned by your login endpoint. In a real application,
use your API's full URL when the frontend and backend
run on different origins.
Use the auth:sanctum middleware to protect
routes that require authentication.
Route::middleware('auth:sanctum')->group(function () {
Route::get('/dashboard', function (Request $request) {
return response()->json([
'message' => 'Welcome to your dashboard',
'user_id' => $request->user()->id,
]);
});
});
To log out the current token-based session, revoke the token used for the current request.
Route::middleware('auth:sanctum')->post(
'/logout',
function (Request $request) {
$request->user()
->currentAccessToken()
?->delete();
return response()->json([
'message' => 'Logged out successfully',
]);
}
);
This logout example is intended for personal access token authentication. Cookie-based SPA authentication has a different session logout flow.
Remember:
Authentication confirms who the user is. Authorization determines what the user is allowed to do.
Build a simple token-authenticated Student API.
HasApiTokens trait to the User model./api/profile endpoint.Bonus Task:
Create a protected /api/students endpoint
that returns student records only to authenticated users.
1. What is Laravel Sanctum used for?
2. Which trait enables personal access token creation?
3. Which middleware protects routes using Sanctum authentication?