PHPackages                             cloudstudio/token-usage - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. cloudstudio/token-usage

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

cloudstudio/token-usage
=======================

This is my package token-usage

112

Since Jan 8Compare

[ Source](https://github.com/cloudstudio/token-usage)[ Packagist](https://packagist.org/packages/cloudstudio/token-usage)[ RSS](/packages/cloudstudio-token-usage/feed)WikiDiscussions Synced today

READMEChangelog (1)DependenciesVersions (1)Used By (0)

Token-Usage Laravel Package
===========================

[](#token-usage-laravel-package)

Token-Usage is a Laravel package that provides advanced token management functionalities for Laravel applications. It offers features for tracking token usage, setting token limits based on different time periods, and integrating these checks easily into Laravel applications. This package is ideal for developers looking to efficiently manage and monitor token consumption in their Laravel projects.

The main idea is to track and manage token usage for AI services. For example, if a SaaS platform charges $10 for 1000 tokens, this package can efficiently monitor and manage the token consumption. It is perfect to work with OpenAI, [ollama](https://packagist.org/packages/cloudstudio/ollama-laravel) for enhanced functionality, etc.

Installation
------------

[](#installation)

```
composer require cloudstudio/token-usage
```

Configuration
-------------

[](#configuration)

Publish the package configuration file:

```
php artisan vendor:publish --tag="token-usage-config"
```

This will publish a config file with the following structure:

```
return [
    'model_mappings' => [
        'user' => \App\Models\User::class,
        // Add more model mappings here
    ],
    'plans' => [
        'basic' => [
            'model_limits' => [
                'user' => [
                    'daily' => 1,
                    'weekly' => 5,
                    'monthly' => 10,
                    'yearly' => 100,
                ],
                // Define more model limits here
            ],
        ],
        'premium' => [
            // Define premium plan limits...
        ],
    ],
];
```

Additionally, publish the package's migrations:

```
php artisan vendor:publish --tag="token-usage-migrations"
```

These migrations will create tables in your database to store token usage data. The migrations are compatible with UUIDs. If your application doesn't use UUIDs, you can modify the migration files accordingly.

User Setup
----------

[](#user-setup)

For the package to work correctly, your `users` table needs to have a `plan` field. You can add this field by creating a new migration or creating a new accesor in your `User` model. For example, to create a new migration, run the following command:

```
php artisan make:migration add_plan_to_users_table
```

If you prefer using a model accesor, add the following method to your `User` model:

```
public function getPlanAttribute()
{
    return 'basic';
}
```

In the migration file, add the `plan` field, like so:

```
Schema::table('users', function (Blueprint $table) {
    $table->string('plan')->default('basic');
});
```

This field is used to determine the token limit plan associated with each user. This setup is optional but recommended for full functionality.

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

First, remember to add the `HasTokenUsage` trait to your model. This trait can be used with any model.

```
namespace App\Models;

use Cloudstudio\TokenUsage\Traits\TokenUsageTrait;

class User extends Authenticatable
{
    use TokenUsageTrait;
    // Other model methods and properties
}
```

With this setup, you are ready to work with tokens. Here are some examples:

```
// Access a model record
$project = Project::first();

// Add tokens
$project->addTokens(3);

// Remove tokens
$project->removeTokens(3);

// Reset tokens
$project->resetTokens();

// Show token records
$tokensToday = $project->dailyTokens();
$tokensThisWeek = $project->weeklyTokens();
$tokensThisMonth = $project->monthlyTokens();
$tokensThisYear = $project->yearlyTokens();

// Show token usage sum
$tokensUsedToday = $project->dailyTokens()->sum("tokens_used");

// Show token usage per model

$tokensPerModel = Project::getDailyTokens();
```

For blade directives, middleware and form you can use 2 parameters.

1º Parameter: The name of the model. (video, user). 2º Parameter: The name of the plan. (daily, weekly, monthly, yearly).

This information is stored in the config file.

All records have user\_id assigned, so if you use directly user as model, you can get all records of the user for all models, so you can know how many tokens have been used by the user, globally.

### Blade Directive

[](#blade-directive)

Easily check for token availability in Blade templates:

```
@hasTokenUsage('video', 'daily')
    I have tokens
@endHasTokenUsage
```

### Route Middleware

[](#route-middleware)

Protect routes using token usage middleware:

```
Route::get('/test-token-usage', function () {
    return response()->json(['message' => 'You have tokens available!']);
})->middleware('check-token-usage:video,daily');
```

### Form Request Validation

[](#form-request-validation)

Validate token usage in form requests:

```
$request->validate([
    'field' => [new \Cloudstudio\TokenUsage\Rules\TokenUsageRule('video', 'daily')],
]);
```

Testing
-------

[](#testing)

Run tests using Pest PHP:

```
pest
```

Changelog, Contributing, and Security
-------------------------------------

[](#changelog-contributing-and-security)

- [Changelog](CHANGELOG.md)
- [Contributing](CONTRIBUTING.md)

Credits
-------

[](#credits)

- [Toni Soriano](https://github.com/cloudstudio)

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT License](LICENSE.md).

###  Health Score

14

—

LowBetter than 1% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity20

Early-stage or recently created project

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3589377?v=4)[Toni Soriano](/maintainers/cloudstudio)[@cloudstudio](https://github.com/cloudstudio)

### Embed Badge

![Health badge](/badges/cloudstudio-token-usage/health.svg)

```
[![Health](https://phpackages.com/badges/cloudstudio-token-usage/health.svg)](https://phpackages.com/packages/cloudstudio-token-usage)
```

###  Alternatives

[martin1982/live-broadcast-bundle

Bundle for live-streaming to various online networks

502.5k1](/packages/martin1982-live-broadcast-bundle)[skecskes/calendar

Laravel 5 Flexible Calendar

144.3k](/packages/skecskes-calendar)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
