Menu

Laravel Sanctum API Authentication: Step-by-Step Guide for Beginners
📰

Laravel Sanctum API Authentication: Step-by-Step Guide for Beginners

DEV Community: laravel·Pial Mahmud·about 19 hours ago
#s6hC5sul
#devtolaravel#devto#dev#token#user
Reading 0:00
15s threshold

Introduction

Laravel Sanctum is a lightweight package for API token authentication. If you are building a Vue, React, or mobile app that needs to log in to a Laravel backend, Sanctum makes it simple.

In this guide, you will learn how to:

Build registration and login APIs;

Generate access tokens

Protect routes with authentication;

Delete the token on logout

Requirements: PHP 8.2+, Composer, and basic Laravel knowledge.

Step 1: Create a Laravel Project

bash composer create-project laravel/laravel sanctum-auth cd sanctum-auth

Enter fullscreen mode

Exit fullscreen mode

Step 2: Install Sanctum

In Laravel 11 and 12, one command sets up API scaffolding:

bash php artisan install:api

Enter fullscreen mode

Exit fullscreen mode

This installs Sanctum, creates routes/api.php, and publishes the personal access tokens migration.

Configure your database in .env (SQLite or MySQL), then run:

bash php artisan migrate

Enter fullscreen mode

Exit fullscreen mode

Step 3: Add the Trait to the User Model

Open…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.