Laravel Sanctum: A Fast and Easy Way to Protect Your REST API
Laravel Sanctum is a powerful package designed to simplify securing your REST API. It’s ideal for scenarios where users need to build services on top of your application. While the official documentation provides detailed instructions, this guide will help you set up Sanctum quickly and effectively.
Step 1: Install Laravel Sanctum
Sanctum comes pre-installed in new Laravel projects. If it’s missing from your setup, you can install it using Composer:
composer require laravel/sanctum
Next, publish Sanctum’s configuration and migration files:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Finally, run the migrations to update your database schema:
php artisan migrate
Step 2: Enable API Token Creation
To allow users to generate tokens for API access, include the HasApiTokens
trait in your User
model:
namespace App\Models;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
}
With this setup, you can create tokens using the createToken
method: