How to use Sanctum in Laravel

AuthorSumit Dey Sarkar

Pubish Date21 Mar 2023

categoryLaravel

In this tutorial we will learn how to use sanctum in Laravel.

Sanctum is a Laravel package which provides a  easy-to-use and lightweight authentication system for single-page applications (SPAs), mobile applications, and simple, token-based APIs. Sanctum uses Laravel's built-in authentication system and adds a simple, token-based authentication layer on top of it.

 

How to use sanctum in Laravel

To use Sanctum in Laravel, follow these steps:

 

Step 1 - Install sanctum package

composer require laravel/sanctum

 

Step 2 - Run the migrations for Sanctum:

php artisan migrate

 

Step 3 - Publish Sanctum's configuration file:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

 

Step 4 - Configure your API to use Sanctum's middleware by adding the `api` middleware group to your API routes in the `routes/api.php` file:

Route::middleware('auth:sanctum')->group(function () {
    // Your API routes here
});

 

Step 5 - In your config/auth.php file, add `sanctum` as a driver for your API guard:

'guards' => [
    'api' => [
        'driver' => 'sanctum',
        'provider' => 'users',
        'hash' => false,
    ],
],

 

Step 6 - Create an authentication token for your user:

$token = $user->createToken('token-name')->plainTextToken;

 

Step 7 - Use the token to authenticate API requests:

$response = $client->request('GET', '/api/user', [
    'headers' => [
        'Authorization' => 'Bearer '.$token,
    ],
]);

 

That's it! Now you can use Sanctum to authenticate API requests in your Laravel application.

Comments 0

Leave a comment