DEV Community

Dhiecoderweb
Dhiecoderweb

Posted on Originally published at dhiecoderweb.com

How to Build a REST API with Laravel Sanctum

Building a REST API with authentication looks complicated, but Laravel Sanctum makes it simple. Sanctum is a great fit for APIs used by mobile apps or SPA front-ends (Vue/React). This article guides you through building an API with token-based login from scratch.

Step 1: Install Sanctum

composer require laravel/sanctum
php artisan migrate
Enter fullscreen mode Exit fullscreen mode

In the latest Laravel versions, Sanctum is automatically ready to use for API tokens without complicated additional configuration.

Step 2: Set Up the User Model

Make sure the User model uses the HasApiTokens trait:

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}
Enter fullscreen mode Exit fullscreen mode

This is only part of the article. For the full discussion, with examples and step-by-step details, you can read it on the original source:

How to Build a REST API with Laravel Sanctum

More programming tutorials and developer tools are also available at dhiecoderweb.com.

Top comments (0)