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 a skilled programmer specializing in Vue.js/Nuxt.js for front-end development and PHP Laravel for back-end solutions. I have a strong focus on API design and development, complemented by experience in web server setup and maintenance. My versatile expertise ensures seamless creation and maintenance of web applications, covering everything from intuitive user interfaces to robust server-side functionality. Passionate about coding and driven by a lifelong learning mindset, I invite you to explore more at danyal.dk.