---
title: "Laravel 13: API Authentication using Sanctum Example"
url: "https://magecomp.com/blog/laravel-13-api-authentication-using-sanctum/"
date: "2026-05-25T11:46:03+00:00"
modified: "2026-05-25T11:46:05+00:00"
author:
  name: "Bharat Desai"
  url: "https://magecomp.com"
categories:
  - "Laravel"
word_count: 703
reading_time: "4 min read"
summary: "This blog will show you how to use Laravel 13 with Sanctum for API Authentication."
description: "Learn how to implement API authentication in Laravel 13 using Sanctum with a complete step-by-step example."
keywords: "Laravel"
language: "en"
schema_type: "Article"
related_posts:
  - title: "Optimizing Laravel Blade: Unlocking Advanced Fetcher Techniques"
    url: "https://magecomp.com/blog/laravel-blade-advanced-fetcher-techniques/"
  - title: "Testing All Routes in Laravel with Pest"
    url: "https://magecomp.com/blog/test-all-routes-in-laravel-with-pest/"
  - title: "How to Create Dummy Data for Testing using Factory in Laravel 11?"
    url: "https://magecomp.com/blog/create-dummy-data-for-testing-using-factory-laravel-11/"
---

# Laravel 13: API Authentication using Sanctum Example

_Published: May 25, 2026_  
_Author: Bharat Desai_  

![Laravel 13 API Authentication using Sanctum Example](https://magecomp.com/blog/wp-content/uploads/2026/05/Laravel-13-API-Authentication-using-Sanctum-Example-1024x512.webp)

This blog will show you how to use Laravel 13 with Sanctum for API Authentication.

The simple and light API authentication provided by Sanctum allows for token authentication for SPA applications, mobile applications, and APIs in Laravel that use tokens. The user of the application can authenticate themselves through the use of the API token. With Laravel version 13, the framework itself uses Sanctum, making it straightforward to implement API authentication due to built-in packages. Here, we are going to demonstrate an example of PHP API authentication with the Laravel 13 Sanctum library.

Here, we are going to create a practical example of PHP API Authentication using the Laravel 13 Sanctum library.

[![Laravel Development Services](https://magecomp.com/blog/wp-content/uploads/2024/12/Laravel-Development-Services-4-1024x284.webp)](https://magecomp.com/services/laravel-development-services/)

## Steps for Laravel 13 API Authentication using Sanctum
- Step 1: Install Laravel 13
- Step 2: Install Laravel Sanctum
- Step 3: Configure Sanctum
- Step 4: Run Migration
- Step 5: Create Authentication Controller
- Step 6: Create API Routes
- Step 7: Test API Authentication
- Run Laravel Application

### Step 1: Install Laravel 13
To begin with, first create a new Laravel application from scratch using the following command:

```
composer create-project laravel/laravel example-app
```

### Step 2: Install Laravel Sanctum
Next, install the Laravel Sanctum package using the following command

```
composer require laravel/sanctum
```

Publish the sanctum configuration file and migration by using the following command:

```
php artisan vendor:publish –provider="LaravelSanctumSanctumServiceProvider"
```

### Step 3: Configure Sanctum
Now add Sanctum middleware and configuration.

Update the **app/Models/User.php** file:

```
<?php
namespace AppModels;
use LaravelSanctumHasApiTokens;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
    protected $hidden = [
        'password',
        'remember_token',
    ];
}
```

### Step 4: Run Migration
Execute the migration using the following command:

```
php artisan migrate
```

### Step 5: Create Authentication Controller
Now, create an Authentication Controller using the following command:

```
php artisan make:controller Api/AuthController
```

Now update the following code in:

**app/Http/Controllers/Api/AuthController.php**

```
<?php
namespace AppHttpControllersApi;
use AppHttpControllersController;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesHash;
use AppModelsUser;
class AuthController extends Controller
{
    /**
     * Register User
     */
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
        ]);
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);
        $token = $user->createToken('auth_token')->plainTextToken;
        return response()->json([
            'message' => 'User Registered Successfully',
            'token' => $token,
            'user' => $user
        ]);
    }
    /**
     * Login User
     */
    public function login(Request $request)
    {
        if (!Auth::attempt($request->only('email', 'password'))) {
            return response()->json([
                'message' => 'Invalid Credentials'
            ], 401);
        }
        $user = User::where('email', $request->email)->first();
        $token = $user->createToken('auth_token')->plainTextToken;
        return response()->json([
            'message' => 'Login Successfully',
            'token' => $token,
            'user' => $user
        ]);
    }
    /**
     * Get Authenticated User
     */
    public function profile(Request $request)
    {
        return response()->json($request->user());
    }
    /**
     * Logout User
     */
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json([
            'message' => 'Logout Successfully'
        ]);
    }
}
```

### Step 6: Create API Routes
Now update the following code in:

**routes/api.php**

```
<?php
use IlluminateSupportFacadesRoute;
use AppHttpControllersApiAuthController;
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 7: Test API Authentication
Now test the API routes using Postman.

**Register API**

```
Method: POST
http://127.0.0.1:8000/api/register
Request Body:
{
"name": "Admin",
"email": "admin@example.com",
"password": "123456"
}
```

**Login API**

```
Method: POST
http://127.0.0.1:8000/api/login
Request Body:
{
"email": "admin@example.com",
"password": "123456"
}
```

After successful login, you will receive an API token. Use this token in the Authorization Header:

```
Bearer YOUR_TOKEN
```

**Profile API**

```
Method: GET
http://127.0.0.1:8000/api/profile
```

**Logout API**

```
Method: POST
http://127.0.0.1:8000/api/logout
```

### Run Laravel App
```
php artisan serve
```

## Conclusion:
Using Laravel Sanctum is one of the easiest and most secure ways to implement API authentication in Laravel applications.

[![Hire laravel Developer](https://magecomp.com/blog/wp-content/uploads/2024/12/Hire-Laravel-Expert-Now-3-1024x284.webp)](https://magecomp.com/services/hire-laravel-developer/)**Happy Coding!**

## FAQ
**1. What is Laravel Sanctum used for?**

Laravel Sanctum is mainly used for token-based API authentication in Laravel applications.

**2. Is Sanctum better than Passport?**

If we consider weight, Laravel Passport is heavier than Sanctum. If you need a full OAuth2 authentication system, then use Passport.

**3. Can I use Sanctum for mobile apps?**

Yes, Laravel Sanctum can be used for mobile application API authentication, including Android and iOS apps.


---

_View the original post at: [https://magecomp.com/blog/laravel-13-api-authentication-using-sanctum/](https://magecomp.com/blog/laravel-13-api-authentication-using-sanctum/)_  
_Served as markdown by [Third Audience](https://github.com/third-audience) v3.5.3_  
_Generated: 2026-05-25 14:33:36 UTC_  
