Laravel Sanctum: Create a token

In Laravel Sanctum, you can create a token for a user through various authentication mechanisms. One common way is by using the Sanctum’s built-in CreateFreshApiToken middleware, which automatically attaches a token to the authenticated user’s session.

Here are the general steps to create a token using Laravel Sanctum:

Install and Set Up Sanctum:
Make sure you have Laravel Sanctum installed and configured. If not, you can install it using Composer:

composer require laravel/sanctum

After installation, publish the Sanctum configuration:

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

Then, run the migrations to set up the necessary database tables:

php artisan migrate

Update User Model: Ensure your User model uses the HasApiTokens trait. Open the User model (app/Models/User.php) and add the trait:

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
    use HasApiTokens, Notifiable;

    // Rest of the model code...

Create a Token: You can create a token for a user using the createToken method. This can be done in a controller, during user registration, or in any other appropriate place.

use Illuminate\Support\Facades\Auth;

public function createToken()
    $user = Auth::user();
    $token = $user->createToken('token-name');

    return response()->json([
        'access_token' => $token->plainTextToken,
        'token_type' => 'Bearer',

This code snippet assumes you’re creating a token for the currently authenticated user. Adjust it as needed for your specific use case.

Protect Routes: To protect routes with Sanctum, you can use the auth:sanctum middleware in your route definition:

Route::middleware('auth:sanctum')->get('/protected-route', function () {
    // Your protected route logic here...

Make sure the request includes the Authorization header with the Bearer token when accessing protected routes.

Remember that these are basic steps, and you might need to adapt them based on your specific requirements and application structure. Always refer to the official Laravel Sanctum documentation for the most up-to-date and detailed information: Laravel Sanctum Documentation.

Credits: ChatGPT 3.5

Author: Danyal
I'm skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting