In this tutorial, I will show you how to build a complete REST API Authentication in Laravel 12 using Sanctum with MySQL Database. API authentication is essential when building modern web applications or mobile applications that need to communicate with a backend server.
Laravel Sanctum provides a simple way to authenticate users and protect API routes using token-based authentication (Bearer Token).
We will create the following APIs:
We will use:
First, create a new Laravel 12 project using Composer:
laravel new laravel12-sanctum-auth
Now, install the Laravel Sanctum package:
composer require laravel/sanctum
Install api.php file using the following command.
php artisan install:api
Open the env file and configure your database:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel12api
DB_USERNAME=root
DB_PASSWORD=
Now run the migration:
php artisan migrate
Now open your User model from:
app/Models/User.php
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}
Now, create a new controller for handling authentication:
php artisan make:controller API/AuthController
Open the AuthController.php and add the following code:
app/Http/Controllers/API/AuthController.php
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Validator;
class AuthController extends Controller
{
// User Registration API
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
}
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$token = $user->createToken('MyAppToken')->plainTextToken;
return response()->json([
'success' => true,
'message' => 'User registered successfully.',
'token' => $token,
'user' => $user,
]);
}
// User Login API
public function login(Request $request)
{
if (!Auth::attempt($request->only('email', 'password'))) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$user = Auth::user();
$token = $user->createToken('MyAppToken')->plainTextToken;
return response()->json([
'success' => true,
'message' => 'Login successful.',
'token' => $token,
'user' => $user,
]);
}
// User Profile API (Protected)
public function profile(Request $request)
{
return response()->json([
'success' => true,
'user' => $request->user(),
]);
}
// User Logout API
public function logout(Request $request)
{
$request->user()->tokens()->delete();
return response()->json([
'success' => true,
'message' => 'Logout successful.',
]);
}
}
Now open your routes/api.php file:
use App\Http\Controllers\API\AuthController;
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
Route::middleware('auth:sanctum')->group(function () {
Route::get('/profile', [AuthController::class, 'profile']);
Route::post('/logout', [AuthController::class, 'logout']);
});
1. Register API
POST:
http://localhost:8000/api/register
Body:
{
"name": "John Doe",
"email": "[email protected]",
"password": "123456",
"password_confirmation": "123456"
}
2. Login API
POST:
http://localhost:8000/api/login
Body:
{
"email": "[email protected]",
"password": "123456"
}
3. Profile API (Protected)
GET:
http://localhost:8000/api/profile
Header:
Authorization: Bearer YOUR_TOKEN
4. Logout API
POST:
http://localhost:8000/api/logout
Header:
Authorization: Bearer YOUR_TOKEN
You might also like: