Introduction
Laravel Sanctum is a powerful package that simplifies API authentication in Laravel applications. Whether you're building a mobile app or providing API access to your web application, Sanctum can help secure your endpoints. In this guide, we will explore the basics of using Laravel Sanctum for API authentication.
Prerequisites
Before we begin, make sure you have the following prerequisites:
- An existing Laravel project
- Basic knowledge of Laravel and API development
- Composer installed
Step 1: Install Laravel Sanctum
Start by installing Laravel Sanctum using Composer:
composer require laravel/sanctum
Then, publish the Sanctum configuration and migration files:
php artisan vendor:publish --tag=sanctum-config
php artisan vendor:publish --tag=sanctum-migrations
And run the migration to create the necessary database tables:
php artisan migrate
Step 2: Configure Sanctum
In your Laravel application, configure Sanctum in the `config/sanctum.php` file. Set the domain and paths that should be allowed to access your API:
'stateful' => env('SANCTUM_STATEFUL_DOMAINS', ['your-app.com']),
'stateless' => env('SANCTUM_STATELESS_DOMAINS', ['api.your-app.com']),
Step 3: Create API Routes
In your `routes/api.php` file, define the routes you want to protect with Sanctum authentication. You can use the `sanctum` middleware to secure these routes:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Step 4: Authenticate Users
To authenticate users, you can use Sanctum's built-in authentication methods. For example, you can create tokens for users and use them to make authenticated API requests:
$user = User::find(1);
$token = $user->createToken('api-token')->plainTextToken;
Conclusion
Laravel Sanctum simplifies API authentication, making it accessible for beginners and experienced developers alike. By following the steps outlined in this guide, you can secure your API endpoints and build a robust API for your application.