About Services Projects Blog Contact
🔐 Laravel · Published on 2025-01-15

How to Build a Professional API with Laravel Sanctum

A comprehensive guide to building a secure, scalable API using Laravel Sanctum with best practices for authentication and security.

🔐

Introduction

Laravel Sanctum provides a featherweight authentication system for SPAs and mobile applications. In this article we'll explore how to set it up professionally.

Installation

First, install Sanctum via Composer:

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Setup

In your User model, add the trait:

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}

Creating Tokens

After login, issue the user a token:

$token = $user->createToken('auth_token')->plainTextToken;
return response()->json(['token' => $token]);

Protecting Routes

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/profile', [ProfileController::class, 'show']);
});

Conclusion

Laravel Sanctum is the ideal choice for building APIs for modern apps. Simple, secure, and easy to integrate with Flutter and React Native.

🚀 Start Your Project ← Back to Blog

Related Articles