1. Go to this page and download the library: Download kazistm/subscriptions library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
kazistm / subscriptions example snippets
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use KaziSTM\Subscriptions\Traits\HasPlanSubscriptions; // Import the trait
class User extends Authenticatable // or your base model (e.g., Model)
{
use HasPlanSubscriptions; // Use the trait
// ... rest of your model
}
use KaziSTM\Subscriptions\Models\Plan;
use App\Models\User; // Your subscribable model
$user = User::find(1);
$proPlan = Plan::where('slug', 'pro')->firstOrFail();
$premiumPlan = Plan::where('slug', 'premium')->first(); // Assuming a premium plan exists
// --- Create / Retrieve ---
// Create a new subscription named 'main'. The name helps if a model can have multiple subscriptions.
$subscription = $user->newPlanSubscription('main', $proPlan);
// Retrieve the 'main' subscription later
$subscription = $user->planSubscription('main');
// --- Check Status ---
if ($subscription?->active()) { echo "Active!"; } // Not ended, could be on trial or paid period
if ($subscription?->inactive()) { echo "Inactive!"; } // Ended or canceled
if ($subscription?->onTrial()) { echo "On Trial until " . $subscription->trial_ends_at->toDateString(); }
if ($subscription?->canceled()) { echo "Canceled."; } // Cancellation requested/processed
if ($subscription?->ended()) { echo "Current period ended."; } // ends_at is in the past
// --- Modify ---
if ($subscription && $premiumPlan) {
$subscription->changePlan($premiumPlan); // Change plan (handles proration based on config/logic)
echo "Plan changed!";
}
// Cancel subscription at the end of the current billing period
$subscription?->cancel();
// Cancel immediately (ends the current period now)
// $subscription?->cancel(true);
// Renew subscription (e.g., after manual payment or admin action)
// Resets usage for resettable features and sets a new billing cycle (starts_at, ends_at)
// Throws LogicException if subscription was canceled AND has already ended
try {
$subscription?->renew();
echo "Renewed!";
} catch (\LogicException $e) { /* Handle error */ }
// --- Querying ---
$isSubscribedToPro = $user->subscribedTo($proPlan->id); // Check active subscription to specific plan ID
$activePlans = $user->subscribedPlans(); // Get collection of Plan models user is actively subscribed to
$allUserSubscriptions = $user->planSubscriptions; // Get collection of Subscription models for user
$activeUserSubscriptions = $user->activePlanSubscriptions(); // Get collection of active Subscription models for user
// --- Plan Queries ---
// Find plans that offer a certain feature (by Limitation slug)
$plansWithApi = Plan::whereHasLimitationSlug('api-calls')->get();
// Check if a specific plan instance offers a feature
$proPlanHasSupport = $proPlan->hasLimitation('priority-support'); // true
// Assuming $user and $subscription are available
$subscription = $user->planSubscription('main');
$usersSlug = 'users';
$apiCallsSlug = 'api-calls';
$supportSlug = 'priority-support';
// --- Checking Ability ---
// canUseFeature checks boolean features AND depleting quotas
if ($subscription?->canUseFeature($usersSlug)) {
echo "User limit not reached.";
// ... perform action like creating a user ...
// Then record usage:
$subscription->recordFeatureUsage($usersSlug); // Increment by 1
} else {
echo "User limit reached!";
}
if ($subscription?->canUseFeature($supportSlug)) {
echo "Priority support is enabled for this plan.";
}
// --- Recording Usage ---
// Increment usage (default)
$usage = $subscription?->recordFeatureUsage($apiCallsSlug, 15); // Record 15 calls
if ($usage) echo "Recorded usage for {$apiCallsSlug}. New usage: {$usage->used}";
// Set usage to a specific value (non-incremental)
$usage = $subscription?->recordFeatureUsage('storage-gb', 15.5, false);
// --- Reducing Usage ---
// Useful when a resource tied to a quota is removed
$usage = $subscription?->reduceFeatureUsage($usersSlug, 1); // Decrement by 1
if ($usage) echo "Reduced usage for {$usersSlug}. New usage: {$usage->used}";
// --- Retrieving Usage Data ---
$currentApiUsage = $subscription?->getFeatureUsage($apiCallsSlug);
$remainingApiCalls = $subscription?->getFeatureRemainings($apiCallsSlug);
$apiLimitOnPlan = $subscription?->getFeatureValue($apiCallsSlug); // Gets the value from the features table
echo "API Calls: Used={$currentApiUsage}, Limit={$apiLimitOnPlan}, Remaining={$remainingApiCalls}";
// --- Resets ---
// If 'api-calls' feature has resettable_interval='month' and resettable_period=1,
// when recordFeatureUsage() is called after the 'valid_until' date on the usage record,
// the 'used' count automatically resets to 0, and 'valid_until' is updated for the next period.
// bootstrap/app.php
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(...)
->withRouting(...)
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'subscription.active' => \KaziSTM\Subscriptions\Http\Middleware\CheckSubscription::class,
'subscription.feature' => \KaziSTM\Subscriptions\Http\Middleware\CheckPlanFeatures::class,
// Add other aliases here
]);
// Optionally add globally to groups if needed
// $middleware->web(append: [ ... ]);
})
->withExceptions(...)
->create();
// app/Http/Kernel.php
protected $middlewareAliases = [ // Or $routeMiddleware in older versions
// ... other aliases
'subscription.active' => \KaziSTM\Subscriptions\Http\Middleware\CheckSubscription::class,
'subscription.feature' => \KaziSTM\Subscriptions\Http\Middleware\CheckPlanFeatures::class,
];
// routes/web.php or routes/api.php
// Checks Auth::user()'s 'main' subscription
Route::get('/dashboard', /* ... */)->middleware(['auth', 'subscription.active']);
// Checks 'main' subscription for the {company} route model (if Company uses the trait)
Route::get('/company/{company}/settings', /* ... */)->middleware(['auth', 'subscription.active']);
// Checks a specific subscription named 'pro_tools' (applies to the found entity)
Route::get('/pro-feature', /* ... */)->middleware(['auth', 'subscription.active:pro_tools']);
// routes/web.php or routes/api.php
// Requires the plan to have the 'users' limitation defined
Route::get('/users/invite', /* ... */)->middleware(['auth', 'subscription.feature:users']);
// Requires both 'reports' and 'exports' limitations
Route::get('/reports/export', /* ... */)->middleware(['auth', 'subscription.feature:reports,exports']);
// Check a specific subscription ('pro_tools') for a specific feature ('advanced-analytics')
Route::get('/analytics/deep-dive', /* ... */)
->middleware(['auth', 'subscription.feature:advanced-analytics,pro_tools']); // Feature slug first, optional subscription slug second
namespace App\Models;
use KaziSTM\Subscriptions\Models\Plan as BasePlan; // Alias is used
class Plan extends BasePlan
{
// Your custom logic here...
}