Laravel 12 REST API Authentication Using Sanctum

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:

  1. Register API – To register a new user.
  2. Login API – To authenticate a user and generate a token.
  3. User Profile API (Protected) – To get the authenticated user details.
  4. Logout API – To destroy the token.

We will use:

  1. Laravel Sanctum for API authentication.
  2. MySQL Database for storing users.
  3. Postman to test the API.

Laravel 12 REST API Authentication Using Sanctum

 

Step 1: Install Laravel 12 Project

First, create a new Laravel 12 project using Composer:

laravel new laravel12-sanctum-auth

 

Step 2: Install Sanctum Package

Now, install the Laravel Sanctum package:

composer require laravel/sanctum

Install api.php file using the following command.

php artisan install:api

 

Step 3: Configure Sanctum

 

Step 4: Setup Database Connection

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

 

Step 5: Update User Model

Now open your User model from:

app/Models/User.php

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}

 

Step 6: Create Authentication Controller

Now, create a new controller for handling authentication:

php artisan make:controller API/AuthController

 

Step 7: Build Register, Login, Profile, and Logout API

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.',
        ]);
    }
}

 

Step 8: Define API Routes

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']);
});

 

Step 9: Test API Using Postman

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:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS