Published on October 24, 2024By DeveloperBreeze

Tutorial: Creating Personal Access Tokens for a Custom Model in Laravel

In this tutorial, we will walk through the process of generating personal access tokens for a custom model in Laravel using Laravel Sanctum. Personal access tokens are useful for authenticating API requests from your application users. We'll demonstrate how to configure a custom model to issue and manage these tokens.

Prerequisites:

  • A Laravel project with the Sanctum package installed.
  • A custom model that you'd like to associate with the tokens.

Step 1: Install Sanctum (If Not Already Installed)

First, make sure Sanctum is installed in your Laravel project. You can install it using Composer:

composer require laravel/sanctum

After installation, publish the Sanctum configuration file:

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

Finally, run the migration to create the necessary tables:

php artisan migrate

Step 2: Model Configuration

Let's assume you have a custom model called Customer. We'll configure this model to issue personal access tokens.

  1. Add the HasApiTokens Trait: In your Customer model, add the HasApiTokens trait, which provides the necessary methods to generate tokens.
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Customer extends Authenticatable
{
    use HasApiTokens;

    protected $fillable = ['name', 'email'];

    // Define the relationship with tokens
    public function tokens()
    {
        return $this->morphMany(\Laravel\Sanctum\PersonalAccessToken::class, 'tokenable');
    }
}

The HasApiTokens trait adds the ability to issue tokens to the Customer model.

Step 3: Generate Personal Access Tokens

Now that your model is configured, let's generate a personal access token for a Customer. You can do this in a controller or any other part of your application where you manage user authentication.

Here’s an example of generating a token for a customer:

$customer = Customer::find($customerId); // Replace $customerId with the actual customer ID
$token = $customer->createToken('customer-token'); // 'customer-token' is the token name
$accessToken = $token->plainTextToken; // This is the plain text token

The $accessToken contains the token string, which you can provide to the customer or use in API requests.

Step 4: Using the Token for Authentication

To authenticate API requests using this token, you can send it in the Authorization header of the request:

GET /api/customer/orders
Host: your-api-domain.com
Authorization: Bearer YOUR_TOKEN_HERE

Laravel will automatically validate the token and authenticate the request if the token is valid.

Step 5: Managing Token Abilities (Optional)

You can also define specific abilities (permissions) for the token to limit what actions a user can perform with that token. For example:

$token = $customer->createToken('customer-token', ['order:view', 'order:create']);

In this case, the token is granted the ability to view and create orders. You can check for these abilities when performing actions in your controllers.

if ($request->user()->tokenCan('order:view')) {
    // The user is allowed to view orders
}

Step 6: Displaying Tokens in Blade View

To display the tokens associated with each Customer in a Blade view, you can loop through the customers and their associated tokens like this:

@foreach ($customers as $customer)
    <div class="customer">
        <p>Customer Name: {{ $customer->name }}</p>

        @if ($customer->tokens->isNotEmpty())
            <p>Personal Access Tokens:</p>
            <ul>
                @foreach ($customer->tokens as $token)
                    <li>
                        <strong>Token Name:</strong> {{ $token->name }}<br>
                        <strong>Token Abilities:</strong> {{ implode(', ', $token->abilities) }}
                    </li>
                @endforeach
            </ul>
        @else
            <p>No personal access tokens available for this customer.</p>
        @endif
    </div>
@endforeach

In the above example:

  • We loop through the $customers collection, displaying each customer's name and their associated tokens.
  • If the customer has any tokens, we display the token name and the abilities assigned to that token.
  • If the customer does not have any tokens, a message is shown indicating that no tokens are available.

Step 7: Revoking Tokens (Optional)

You may want to revoke tokens when a customer logs out or when you need to invalidate a token. This can be done by deleting the token associated with the customer:

$customer->tokens()->delete(); // Revoke all tokens for this customer

Alternatively, you can revoke a specific token:

$customer->tokens()->where('id', $tokenId)->delete(); // Revoke a specific token

Conclusion

In this tutorial, we walked through the process of generating and managing personal access tokens for a custom model in Laravel using Sanctum. This includes setting up your model, creating tokens, using them for API authentication, and displaying them in a Blade view.

By leveraging Laravel Sanctum, you can easily authenticate API requests in a secure and scalable way, while providing flexibility for defining token abilities and managing tokens across different models.

Comments

Please log in to leave a comment.

Continue Reading:

Upload and Store File in Laravel

Published on January 26, 2024

php

Create Event and Listener in Laravel

Published on January 26, 2024

bash

Querying Data from Database Table in Laravel

Published on January 26, 2024

php

Laravel CSRF-Protected Form

Published on January 26, 2024

html

Create Resource Controller in Laravel

Published on January 26, 2024

bash

Laravel Validation Rules for User Registration

Published on January 26, 2024

php

Blade View in Laravel Extending Layout

Published on January 26, 2024

html