### Install Laravel Subscriptions Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Install the package via Composer, publish configuration and migrations, and run migrations to set up the database. ```bash composer require laravelcm/laravel-subscriptions php artisan vendor:publish --provider="Laravelcm\Subscriptions\SubscriptionServiceProvider" php artisan migrate ``` -------------------------------- ### Install Laravel Subscriptions Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Install the package via composer. ```shell composer require laravelcm/laravel-subscriptions ``` -------------------------------- ### Create a New Subscription Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Subscribe a user to a plan using the `newPlanSubscription` method. The first argument is the subscription title (e.g., 'main'), and the second is the plan instance. An optional third argument can specify a custom start date. ```php use Laravelcm\Subscriptions\Models\Plan; use App\Models\User; $user = User::find(1); $plan = Plan::find(1); $user->newPlanSubscription('main', $plan); ``` -------------------------------- ### HasPlanSubscriptions::newPlanSubscription() Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Creates a new subscription for a model to a specific plan. It automatically calculates trial, start, and end dates based on the plan's configuration. Free plans result in non-expiring subscriptions. ```APIDOC ## `HasPlanSubscriptions::newPlanSubscription()` — Creating a Subscription Subscribes a model to a plan, automatically computing `trial_ends_at`, `starts_at`, and `ends_at` from the plan's trial and invoice periods. Free plans receive `null` for both date fields (they never expire). ```php use Laravelcm\Subscriptions\Models\Plan; use App\Models\User; use Carbon\Carbon; $user = User::find(1); $plan = Plan::find(1); // 15-day trial + 1-month billing // Start now (default) $subscription = $user->newPlanSubscription('main', $plan); // trial_ends_at = now + 15 days // starts_at = now + 15 days // ends_at = now + 15 days + 1 month // Start at a future date $subscription = $user->newPlanSubscription('main', $plan, Carbon::parse('2025-06-01')); // Free plan — never expires $freePlan = Plan::create(['name' => 'Free', 'price' => 0, 'invoice_interval' => 'month', 'invoice_period' => 1]); $sub = $user->newPlanSubscription('free-tier', $freePlan); echo $sub->ends_at; // null echo $sub->trial_ends_at; // null ``` ``` -------------------------------- ### Retrieve Plan Details Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Query a plan to get its features, subscriptions, and check its properties like being free, having a trial, or grace period. Relations can be queried like normal Eloquent relationships. ```php use Laravelcm\Subscriptions\Models\Plan; $plan = Plan::find(1); // Get all plan features $plan->features; // Get all plan subscriptions $plan->subscriptions; // Check if the plan is free $plan->isFree(); // Check if the plan has trial period $plan->hasTrial(); // Check if the plan has grace period $plan->hasGrace(); ``` -------------------------------- ### Get Feature Value Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Retrieve the value of a specific feature for a plan or subscription. Ensure the feature exists and is accessible. ```php use Laravelcm\Subscriptions\Models\Feature; use Laravelcm\Subscriptions\Models\Subscription; // Use the plan instance to get feature's value $amountOfPictures = $plan->getFeatureBySlug('pictures_per_listing')->value; // Query the feature itself directly $amountOfPictures = Feature::where('slug', 'pictures_per_listing')->first()->value; // Get feature value through the subscription instance $amountOfPictures = Subscription::find(1)->getFeatureValue('pictures_per_listing'); ``` -------------------------------- ### Calculate Billing Periods with Period Service Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt The `Period` service is a low-level helper for custom date arithmetic, used internally for creating new subscription periods. Instantiate it with an interval type, count, and an optional start date. ```php use Laravelcm\Subscriptions\Services\Period; use Carbon\Carbon; // Monthly period starting now $period = new Period(interval: 'month', count: 1); echo $period->getStartDate()->toDateString(); // today echo $period->getEndDate()->toDateString(); // today + 1 month // 3-month period from a specific date $period = new Period('month', 3, Carbon::parse('2025-01-01')); echo $period->getStartDate()->toDateString(); // "2025-01-01" echo $period->getEndDate()->toDateString(); // "2025-04-01" // Annual period $period = new Period('year', 1, Carbon::now()); echo $period->getInterval(); // "year" echo $period->getIntervalCount(); // 1 // Daily period — e.g., for computing a 15-day trial end date $trial = new Period('day', 15, Carbon::now()); echo $trial->getEndDate()->toDateString(); // today + 15 days ``` -------------------------------- ### Get Feature Reset Date Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Retrieve the reset date for a specific plan feature. This is useful for features with usage limits that reset periodically. ```php use Laravelcm\Subscriptions\Models\Feature; // Find plan feature $feature = Feature::where('name', 'listing_duration_days')->first(); // Get feature reset date $feature->getResetDate(new \Carbon\Carbon()); ``` -------------------------------- ### Run Database Migrations Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Execute migrations to set up the necessary database tables. ```shell php artisan migrate ``` -------------------------------- ### Create a Billing Plan with Features Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Use `Plan::create()` to define a new billing plan, including pricing, billing intervals, trial and grace periods, and an optional subscriber limit. Features can be attached in a batch using `saveMany()`. Plan inspection helpers are available. ```php use Laravelcm\Subscriptions\Models\Plan; use Laravelcm\Subscriptions\Models\Feature; use Laravelcm\Subscriptions\Interval; $plan = Plan::create([ 'name' => 'Pro', 'description' => 'Pro plan', 'is_active' => true, 'price' => 9.99, 'signup_fee' => 1.99, 'currency' => 'USD', 'invoice_period' => 1, 'invoice_interval' => Interval::MONTH->value, // billing cycle length 'trial_period' => 15, 'trial_interval' => Interval::DAY->value, 'grace_period' => 3, 'grace_interval' => Interval::DAY->value, 'active_subscribers_limit'=> 100, 'sort_order' => 1, ]); // Attach features in one batch $plan->features()->saveMany([ new Feature(['name' => 'listings', 'value' => '50', 'sort_order' => 1]), new Feature(['name' => 'pictures_per_listing', 'value' => '10', 'sort_order' => 5]), new Feature([ 'name' => 'listing_duration_days', 'value' => '30', 'sort_order' => 10, 'resettable_period' => 1, 'resettable_interval' => Interval::MONTH->value, // usage resets monthly ]), new Feature(['name' => 'listing_title_bold', 'value' => 'true', 'sort_order' => 15]), ]); // Plan inspection helpers $plan->isFree(); // false — price > 0 $plan->hasTrial(); // true — trial_period & trial_interval set $plan->hasGrace(); // true — grace_period & grace_interval set ``` -------------------------------- ### Create a New Plan Subscription Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Use `HasPlanSubscriptions::newPlanSubscription()` to subscribe a model to a plan. This method automatically calculates `trial_ends_at`, `starts_at`, and `ends_at` based on the plan's configuration. For free plans, these dates are set to null. ```php use Laravelcm\Subscriptions\Models\Plan; use App\Models\User; use Carbon\Carbon; $user = User::find(1); $plan = Plan::find(1); // 15-day trial + 1-month billing // Start now (default) $subscription = $user->newPlanSubscription('main', $plan); // trial_ends_at = now + 15 days // starts_at = now + 15 days // ends_at = now + 15 days + 1 month // Start at a future date $subscription = $user->newPlanSubscription('main', $plan, Carbon::parse('2025-06-01')); // Free plan — never expires $freePlan = Plan::create(['name' => 'Free', 'price' => 0, 'invoice_interval' => 'month', 'invoice_period' => 1]); $sub = $user->newPlanSubscription('free-tier', $freePlan); echo $sub->ends_at; // null echo $sub->trial_ends_at; // null ``` -------------------------------- ### Publish Package Resources Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Publish migrations and config files for the package. ```shell php artisan vendor:publish --provider="Laravelcm\Subscriptions\SubscriptionServiceProvider" ``` -------------------------------- ### Plan::create() Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Creates a new billing plan with specified pricing, billing frequency, trial, grace periods, and an optional subscriber cap. Supports array translations for name and description. ```APIDOC ## `Plan::create()` — Creating a Plan Creates a billing plan with pricing, billing frequency, trial period, grace period, and an optional subscriber cap. `name` and `description` support arrays for translations. ```php use Laravelcm\Subscriptions\Models\Plan; use Laravelcm\Subscriptions\Models\Feature; use Laravelcm\Subscriptions\Interval; $plan = Plan::create([ 'name' => 'Pro', // or ['en' => 'Pro', 'fr' => 'Pro'] 'description' => 'Pro plan', 'is_active' => true, 'price' => 9.99, 'signup_fee' => 1.99, 'currency' => 'USD', 'invoice_period' => 1, 'invoice_interval' => Interval::MONTH->value, // billing cycle length 'trial_period' => 15, 'trial_interval' => Interval::DAY->value, 'grace_period' => 3, 'grace_interval' => Interval::DAY->value, 'active_subscribers_limit'=> 100, 'sort_order' => 1, ]); // Attach features in one batch $plan->features()->saveMany([ new Feature(['name' => 'listings', 'value' => '50', 'sort_order' => 1]), new Feature(['name' => 'pictures_per_listing', 'value' => '10', 'sort_order' => 5]), new Feature([ 'name' => 'listing_duration_days', 'value' => '30', 'sort_order' => 10, 'resettable_period' => 1, 'resettable_interval' => Interval::MONTH->value, // usage resets monthly ]), new Feature(['name' => 'listing_title_bold', 'value' => 'true', 'sort_order' => 15]), ]); // Plan inspection helpers $plan->isFree(); // false — price > 0 $plan->hasTrial(); // true — trial_period & trial_interval set $plan->hasGrace(); // true — grace_period & grace_interval set ``` ``` -------------------------------- ### Create a New Plan Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Create a new plan with specified details and associate multiple features with it. Features can have resettable periods and intervals. ```php use Laravelcm\Subscriptions\Models\Plan; use Laravelcm\Subscriptions\Models\Feature; use Laravelcm\Subscriptions\Interval; $plan = Plan::create([ 'name' => 'Pro', 'description' => 'Pro plan', 'price' => 9.99, 'signup_fee' => 1.99, 'invoice_period' => 1, 'invoice_interval' => Interval::MONTH->value, 'trial_period' => 15, 'trial_interval' => Interval::DAY->value, 'sort_order' => 1, 'currency' => 'USD', ]); // Create multiple plan features at once $plan->features()->saveMany([ new Feature(['name' => 'listings', 'value' => 50, 'sort_order' => 1]), new Feature(['name' => 'pictures_per_listing', 'value' => 10, 'sort_order' => 5]), new Feature(['name' => 'listing_duration_days', 'value' => 30, 'sort_order' => 10, 'resettable_period' => 1, 'resettable_interval' => 'month']), new Feature(['name' => 'listing_title_bold', 'value' => 'Y', 'sort_order' => 15]) ]); ``` -------------------------------- ### Change Subscription Plan with `changePlan()` Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Switches a user's subscription to a different plan. If billing frequency changes, the period resets and usage data is cleared. If frequencies match, billing dates are preserved. ```php use Laravelcm\Subscriptions\Models\Plan; use App\Models\User; $user = User::find(1); $premiumPlan = Plan::find(2); // same invoice_period/interval as current plan // Upgrade — billing dates retained because frequency matches $user->planSubscription('main')->changePlan($premiumPlan); $yearlyPlan = Plan::create([ 'name' => 'Yearly Pro', 'price' => 99.99, 'invoice_period' => 1, 'invoice_interval' => 'year', ]); // Downgrade/change frequency — resets period & clears usage $user->planSubscription('main')->changePlan($yearlyPlan); // New starts_at = today, ends_at = today + 1 year // All feature usage records deleted ``` -------------------------------- ### Subscription::changePlan() Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Switches a subscription to a different plan. Handles upgrades and downgrades, resetting the billing period and usage data if the billing frequency changes. ```APIDOC ## `Subscription::changePlan()` — Upgrading or Downgrading Switches a subscription to a different plan. If billing frequency changes, the period resets to today and all usage data is cleared. If frequencies match, billing dates are preserved. ### Usage ```php use Laravelcm\Subscriptions\Models\Plan; use App\Models\User; $user = User::find(1); $premiumPlan = Plan::find(2); // same invoice_period/interval as current plan // Upgrade — billing dates retained because frequency matches $user->planSubscription('main')->changePlan($premiumPlan); $yearlyPlan = Plan::create([ 'name' => 'Yearly Pro', 'price' => 99.99, 'invoice_period' => 1, 'invoice_interval' => 'year', ]); // Downgrade/change frequency — resets period & clears usage $user->planSubscription('main')->changePlan($yearlyPlan); // New starts_at = today, ends_at = today + 1 year // All feature usage records deleted ``` ``` -------------------------------- ### Renew Subscription with `renew()` Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Extends the subscription by one billing period from today, clearing all usage data. Throws `LogicException` if the subscription is canceled and already ended. ```php use Laravelcm\Subscriptions\Models\Subscription; $subscription = Subscription::find(1); try { $subscription->renew(); // starts_at and ends_at are updated // usage data cleared // canceled_at set to null } catch (\LogicException $e) { // "Unable to renew canceled ended subscription." echo $e->getMessage(); } ``` -------------------------------- ### Retrieve a User's Plan Subscription Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Use `HasPlanSubscriptions::planSubscription()` to retrieve a user's active subscription by its slug. This provides access to methods for checking subscription status, such as `active()`, `onTrial()`, `canceled()`, `ended()`, and `inactive()`. ```php $user = User::find(1); $subscription = $user->planSubscription('main'); // Check status $subscription->active(); // true if not ended, or on trial $subscription->onTrial(); // true while trial_ends_at is in the future $subscription->canceled(); // true after cancel() is called $subscription->ended(); // true after ends_at has passed $subscription->inactive(); // inverse of active() ``` -------------------------------- ### Cancel Subscription with `cancel()` Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Marks a subscription as canceled. By default, access continues until `ends_at`. Pass `true` to terminate access immediately. ```php $user = User::find(1); // Cancel at end of billing period (graceful) $user->planSubscription('main')->cancel(); // canceled_at = now, ends_at unchanged — still active until billing period ends // Cancel immediately $user->planSubscription('main')->cancel(immediately: true); // canceled_at = now, ends_at = now — access revoked immediately $user->planSubscription('main')->canceled(); // true ``` -------------------------------- ### Query Subscriptions with Scopes Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Utilize static scopes on the `Subscription` model for bulk queries, ideal for cron jobs handling renewal reminders or trial expirations. These scopes can be chained with standard Eloquent methods. ```php use Laravelcm\Subscriptions\Models\Subscription; use App\Models\User; // All subscriptions on a given plan Subscription::byPlanId(1)->get(); // All subscriptions belonging to one subscriber $user = User::find(1); Subscription::ofSubscriber($user)->get(); // Trials ending in the next 3 days (default) or custom range Subscription::findEndingTrial(3)->get(); Subscription::findEndingTrial(7)->get(); // 7-day lookahead // Trials that have already ended Subscription::findEndedTrial()->get(); // Billing periods ending soon Subscription::findEndingPeriod(3)->get(); // Billing periods that have already ended Subscription::findEndedPeriod()->get(); // All currently active subscriptions (ends_at in the future) Subscription::findActive()->get(); // Chainable with standard Eloquent Subscription::byPlanId(1)->findEndingPeriod(5)->with('subscriber')->get(); ``` -------------------------------- ### Check Plan Subscription Status with `subscribedTo()` Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Checks if a user has an active subscription to a specific plan ID. Also shows how to retrieve all active plans or all subscription records. ```php $user = User::find(1); $planId = 1; if ($user->subscribedTo($planId)) { // User is actively subscribed } // Get all plans the user is actively subscribed to $activePlans = $user->subscribedPlans(); // Collection of Plan models // Get all subscription records (including inactive) $allSubscriptions = $user->planSubscriptions; // Eloquent Collection $activeOnly = $user->activePlanSubscriptions(); // rejects inactive ones ``` -------------------------------- ### HasPlanSubscriptions::planSubscription() Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Retrieves an active subscription for a model using its slug. This serves as the entry point for managing subscription-related actions. ```APIDOC ## `HasPlanSubscriptions::planSubscription()` — Retrieve a Subscription Fetches an active subscription by its slug (partial match). Use this as the gateway to all per-subscription actions. ```php $user = User::find(1); $subscription = $user->planSubscription('main'); // Check status $subscription->active(); // true if not ended, or on trial $subscription->onTrial(); // true while trial_ends_at is in the future $subscription->canceled(); // true after cancel() is called $subscription->ended(); // true after ends_at has passed $subscription->inactive(); // inverse of active() ``` ``` -------------------------------- ### Apply HasPlanSubscriptions Trait Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Add the `HasPlanSubscriptions` trait to your subscriber model (e.g., `User`) to enable the full subscription API, including relationships, queries, creation, and status checks. ```php // app/Models/User.php namespace App\Models; use Laravelcm\Subscriptions\Traits\HasPlanSubscriptions; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use HasPlanSubscriptions; } ``` -------------------------------- ### Subscription Models Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md List of core models used by the Laravel Subscriptions package. ```php Laravelcm\Subscriptions\Models\Plan; Laravelcm\Subscriptions\Models\Feature; Laravelcm\Subscriptions\Models\Subscription; Laravelcm\Subscriptions\Models\SubscriptionUsage; ``` -------------------------------- ### Configure Laravel Subscriptions Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Customize table names and swappable model classes in the `config/laravel-subscriptions.php` file. You can extend models to add custom logic, such as payment gateway hooks. ```php // config/laravel-subscriptions.php return [ 'tables' => [ 'plans' => 'plans', 'features' => 'features', 'subscriptions' => 'subscriptions', 'subscription_usage' => 'subscription_usage', ], 'models' => [ 'plan' => \Laravelcm\Subscriptions\Models\Plan::class, 'feature' => \Laravelcm\Subscriptions\Models\Feature::class, 'subscription' => \Laravelcm\Subscriptions\Models\Subscription::class, 'subscription_usage' => \Laravelcm\Subscriptions\Models\SubscriptionUsage::class, ], ]; // Swapping to a custom model that, e.g., cancels a Stripe subscription on cancel(): // 'subscription' => \App\Models\Subscription::class, ``` -------------------------------- ### Subscription Query Scopes Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Static query scopes available on the `Subscription` model for performing bulk queries across all subscriptions. These are useful for tasks like sending renewal reminders or expiring trials. ```APIDOC ## `Subscription` Query Scopes — Bulk Subscription Queries Static scopes on the `Subscription` model for querying across all subscriptions — useful for cron jobs that send renewal reminders or expire trials. ```php use Laravelcm\Subscriptions\Models\Subscription; use App\Models\User; // All subscriptions on a given plan Subscription::byPlanId(1)->get(); // All subscriptions belonging to one subscriber $user = User::find(1); Subscription::ofSubscriber($user)->get(); // Trials ending in the next 3 days (default) or custom range Subscription::findEndingTrial(3)->get(); Subscription::findEndingTrial(7)->get(); // 7-day lookahead // Trials that have already ended Subscription::findEndingTrial()->get(); // Billing periods ending soon Subscription::findEndingPeriod(3)->get(); // Billing periods that have already ended Subscription::findEndedPeriod()->get(); // All currently active subscriptions (ends_at in the future) Subscription::findActive()->get(); // Chainable with standard Eloquent Subscription::byPlanId(1)->findEndingPeriod(5)->with('subscriber')->get(); ``` ``` -------------------------------- ### Subscription Model Scopes Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Utilize scopes on the Subscription model for efficient querying. This includes filtering by plan ID, subscriber, trial status, and period end dates. ```php use Laravelcm\Subscriptions\Models\Subscription; use App\Models\User; // Get subscriptions by plan $subscriptions = Subscription::byPlanId($plan_id)->get(); // Get bookings of the given user $user = User::find(1); $bookingsOfSubscriber = Subscription::ofSubscriber($user)->get(); // Get subscriptions with trial ending in 3 days $subscriptions = Subscription::findEndingTrial(3)->get(); // Get subscriptions with ended trial $subscriptions = Subscription::findEndedTrial()->get(); // Get subscriptions with period ending in 3 days $subscriptions = Subscription::findEndingPeriod(3)->get(); // Get subscriptions with ended period $subscriptions = Subscription::findEndedPeriod()->get(); ``` -------------------------------- ### Record Feature Usage Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Track the usage of a feature for a user's subscription. By default, usage is incremented by 1. You can specify a different quantity or override the usage entirely. ```php $user->planSubscription('main')->recordFeatureUsage('listings'); ``` ```php // Increment by 2 $user->planSubscription('main')->recordFeatureUsage('listings', 2); ``` ```php // Override with 9 $user->planSubscription('main')->recordFeatureUsage('listings', 9, false); ``` -------------------------------- ### Subscription::cancel() Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Marks a subscription as canceled. By default, access continues until the end of the current billing period (`ends_at`). An optional `immediately` parameter can be set to `true` to revoke access immediately. ```APIDOC ## `Subscription::cancel()` — Canceling a Subscription Marks a subscription as canceled. By default, access continues until `ends_at`. Pass `true` to terminate access immediately. ### Usage ```php $user = User::find(1); // Cancel at end of billing period (graceful) $user->planSubscription('main')->cancel(); // canceled_at = now, ends_at unchanged — still active until billing period ends // Cancel immediately $user->planSubscription('main')->cancel(immediately: true); // canceled_at = now, ends_at = now — access revoked immediately $user->planSubscription('main')->canceled(); // true ``` ``` -------------------------------- ### Retrieve Plan Feature by Slug Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Use `Plan::getFeatureBySlug()` to fetch a specific feature associated with a plan using its slug. Alternatively, features can be queried directly via the `Feature` model using the `slug` attribute. The `getResetDate()` method can determine the next reset date for resettable features. ```php use Laravelcm\Subscriptions\Models\Plan; use Laravelcm\Subscriptions\Models\Feature; $plan = Plan::find(1); // By plan relationship $feature = $plan->getFeatureBySlug('pictures-per-listing'); echo $feature->value; // "10" // Via Eloquent query $feature = Feature::where('slug', 'listing-duration-days')->first(); echo $feature->value; // "30" // Get next reset date for a resettable feature $resetDate = $feature->getResetDate(new \Carbon\Carbon('2024-01-15')); echo $resetDate->toDateString(); // "2024-02-15" ``` -------------------------------- ### Toggle Plan Availability Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Use `Plan::activate()` and `Plan::deactivate()` to change the `is_active` status of a plan. This prevents new subscriptions without deleting existing plan records. These methods are chainable. ```php $plan = Plan::find(1); $plan->deactivate(); // is_active = false — new subscriptions blocked $plan->activate(); // is_active = true — plan is live again // Chainable Plan::find(2)->deactivate()->activate(); ``` -------------------------------- ### Subscription::renew() Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Renews a subscription, extending it by one billing period from the current date and clearing all associated usage data. Throws a `LogicException` if attempting to renew a canceled and already ended subscription. ```APIDOC ## `Subscription::renew()` — Renewing a Subscription Extends the subscription by one billing period from today, clearing all usage data in the same database transaction. Throws `LogicException` if the subscription is both canceled and already ended. ### Usage ```php use Laravelcm\Subscriptions\Models\Subscription; $subscription = Subscription::find(1); try { $subscription->renew(); // starts_at and ends_at are updated // usage data cleared // canceled_at set to null } catch (\\\LogicException $e) { // "Unable to renew canceled ended subscription." echo $e->getMessage(); } ``` ``` -------------------------------- ### Plan::activate() / Plan::deactivate() Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Toggles the availability of a plan by setting its `is_active` flag. This allows retiring or launching plans without deleting them. ```APIDOC ## `Plan::activate()` / `Plan::deactivate()` — Toggling Plan Availability Fluently toggle a plan's `is_active` flag, allowing you to retire old plans or launch new ones without deleting records. ```php $plan = Plan::find(1); $plan->deactivate(); // is_active = false — new subscriptions blocked $plan->activate(); // is_active = true — plan is live again // Chainable Plan::find(2)->deactivate()->activate(); ``` ``` -------------------------------- ### Using Interval Enum Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Utilize the `Interval` enum for defining plan and feature intervals to prevent magic string errors. It supports 'year', 'month', and 'day'. ```php use Laravelcm\Subscriptions\Interval; echo Interval::MONTH->value; // "month" echo Interval::YEAR->value; // "year" echo Interval::DAY->value; // "day" // Used when creating plans: Plan::create([ 'invoice_interval' => Interval::MONTH->value, 'trial_interval' => Interval::DAY->value, ]); ``` -------------------------------- ### Check Feature Usage Ability Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Determine if a user can use a specific feature based on their subscription. This checks if the feature is enabled, has a value, and has remaining uses. ```php $user->planSubscription('main')->canUseFeature('listings'); ``` -------------------------------- ### Inspect Subscription Features Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Use these methods to check feature status, raw counts, usage, and remaining uses on an active subscription. `canUseFeature` is the primary gate check for application logic. ```php $sub = $user->planSubscription('main'); // Gate check — returns true/false $sub->canUseFeature('listings'); // true if value is "true" // false if value is "false" or "0" // false if usage has expired // true if remaining uses > 0 // Raw counts $sub->getFeatureValue('listings'); // "50" (string from DB) $sub->getFeatureUsage('listings'); // 3 (int — times used) $sub->getFeatureRemainings('listings'); // 47 (int — value minus usage) // Boolean-style feature $sub->canUseFeature('listing-title-bold'); // true (value = "true") // Clear all usage for a subscription $sub->usage()->delete(); ``` -------------------------------- ### Add Subscription Trait to User Model Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Use the HasPlanSubscriptions trait in your User model to enable subscription functionality. This trait can be used on any subscriber model. ```php namespace App\Models; use Laravelcm\Subscriptions\Traits\HasPlanSubscriptions; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use HasPlanSubscriptions; } ``` -------------------------------- ### Change Subscription Plan Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Easily change a user's subscription to a different plan. If billing frequencies match, billing dates are retained. Otherwise, billing dates adjust to the new plan's frequency, and usage data is cleared. Trial periods may apply if the new plan has one. ```php use Laravelcm\Subscriptions\Models\Plan; use Laravelcm\Subscriptions\Models\Subscription; $plan = Plan::find(2); $subscription = Subscription::find(1); // Change subscription plan $subscription->changePlan($plan); ``` -------------------------------- ### Reduce Feature Usage with `reduceFeatureUsage()` Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Decrements the usage counter by a given amount, flooring at 0. Useful for undoing actions like deleting a created listing. ```php $user = User::find(1); // After recording 2 uses of 'deploy-sites' (total = 2): $user->planSubscription('main')->recordFeatureUsage('deploy-sites', 2); // Reduce by 1 (default) $user->planSubscription('main')->reduceFeatureUsage('deploy-sites'); // getFeatureUsage('deploy-sites') => 1 // Reduce by specific amount $user->planSubscription('main')->reduceFeatureUsage('deploy-sites', 2); // getFeatureUsage('deploy-sites') => 0 (floors at 0, never negative) ``` -------------------------------- ### Feature Inspection Methods Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt These methods allow you to inspect the status and usage of features associated with an active subscription. `canUseFeature` is the primary method for application logic checks. ```APIDOC ## `Subscription::canUseFeature()` / `getFeatureUsage()` / `getFeatureRemainings()` / `getFeatureValue()` — Feature Inspection Four methods for reading feature status on the active subscription; `canUseFeature` is the gate check used in application logic. ```php $sub = $user->planSubscription('main'); // Gate check — returns true/false $sub->canUseFeature('listings'); // true if value is "true" // false if value is "false" or "0" // false if usage has expired // true if remaining uses > 0 // Raw counts $sub->getFeatureValue('listings'); // "50" (string from DB) $sub->getFeatureUsage('listings'); // 3 (int — times used) $sub->getFeatureRemainings('listings'); // 47 (int — value minus usage) // Boolean-style feature $sub->canUseFeature('listing-title-bold'); // true (value = "true") // Clear all usage for a subscription $sub->usage()->delete(); ``` ``` -------------------------------- ### Check Subscription Status Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Determine if a user is subscribed to a specific plan. A subscription is active if it has an active trial or its end date is in the future. Canceled subscriptions with an active trial or future end date are still considered active. ```php $user->subscribedTo($planId); ``` ```php $user->planSubscription('main')->active(); $user->planSubscription('main')->canceled(); $user->planSubscription('main')->ended(); $user->planSubscription('main')->onTrial(); ``` -------------------------------- ### Period Service Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt A low-level helper service for performing billing period calculations. It can be used directly when custom date arithmetic is needed, independent of the subscription creation process. ```APIDOC ## `Period` Service — Billing Period Calculations Low-level helper used internally by `HasPlanSubscriptions::newPlanSubscription()` and `Subscription::setNewPeriod()`. Available for direct use when custom date arithmetic is needed. ```php use Laravelcm\Subscriptions\Services\Period; use Carbon\Carbon; // Monthly period starting now $period = new Period(interval: 'month', count: 1); echo $period->getStartDate()->toDateString(); // today echo $period->getEndDate()->toDateString(); // today + 1 month // 3-month period from a specific date $period = new Period('month', 3, Carbon::parse('2025-01-01')); echo $period->getStartDate()->toDateString(); // "2025-01-01" echo $period->getEndDate()->toDateString(); // "2025-04-01" // Annual period $period = new Period('year', 1, Carbon::now()); echo $period->getInterval(); // "year" echo $period->getIntervalCount(); // 1 // Daily period — e.g., for computing a 15-day trial end date $trial = new Period('day', 15, Carbon::now()); echo $trial->getEndDate()->toDateString(); // today + 15 days ``` ``` -------------------------------- ### Reduce Feature Usage Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Decrease the recorded usage of a feature for a user's subscription. By default, usage is reduced by 1. ```php $user->planSubscription('main')->reduceFeatureUsage('listings', 2); ``` -------------------------------- ### Cancel a Subscription Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Cancel a user's subscription. By default, it remains active until the period ends. Pass `true` to cancel immediately. ```php $user->planSubscription('main')->cancel(); ``` ```php $user->planSubscription('main')->cancel(true); ``` -------------------------------- ### Record Feature Usage with `recordFeatureUsage()` Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Increments or overrides the usage counter for a feature. Automatically manages `valid_until` expiry for resettable features. ```php $user = User::find(1); // Default: increment by 1 $usage = $user->planSubscription('main')->recordFeatureUsage('listings'); // $usage->used => 1 // Increment by a custom amount $user->planSubscription('main')->recordFeatureUsage('listings', 3); // $usage->used => 4 // Override (not incremental) — set absolute value $user->planSubscription('main')->recordFeatureUsage('listings', 9, false); // $usage->used => 9 // For resettable features, valid_until is set automatically on first use // and refreshed when expired $user->planSubscription('main')->recordFeatureUsage('listing-duration-days'); // valid_until = subscription_created_at + 1 month ``` -------------------------------- ### Clear Subscription Usage Data Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Delete all recorded usage data for a user's subscription. This effectively resets all feature usage tracking. ```php $user->planSubscription('main')->usage()->delete(); ``` -------------------------------- ### Plan::getFeatureBySlug() Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Retrieves a specific feature associated with a plan using its unique slug. This method provides direct access to feature details and reset schedules. ```APIDOC ## `Plan::getFeatureBySlug()` — Retrieve a Feature from a Plan Fetches the `Feature` model belonging to a plan by its auto-generated slug, enabling direct access to a feature's value and reset schedule. ```php use Laravelcm\Subscriptions\Models\Plan; use Laravelcm\Subscriptions\Models\Feature; $plan = Plan::find(1); // By plan relationship $feature = $plan->getFeatureBySlug('pictures-per-listing'); echo $feature->value; // "10" // Via Eloquent query $feature = Feature::where('slug', 'listing-duration-days')->first(); echo $feature->value; // "30" // Get next reset date for a resettable feature $resetDate = $feature->getResetDate(new \Carbon\Carbon('2024-01-15')); echo $resetDate->toDateString(); // "2024-02-15" ``` ``` -------------------------------- ### HasPlanSubscriptions::subscribedTo() Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Checks if a user has an active subscription to a specific plan ID. Also provides methods to retrieve active plans and all subscription records. ```APIDOC ## `HasPlanSubscriptions::subscribedTo()` — Check Plan Subscription Status Returns `true` if the user has an active subscription to the specified plan ID. ### Usage ```php $user = User::find(1); $planId = 1; if ($user->subscribedTo($planId)) { // User is actively subscribed } // Get all plans the user is actively subscribed to $activePlans = $user->subscribedPlans(); // Collection of Plan models // Get all subscription records (including inactive) $allSubscriptions = $user->planSubscriptions; // Eloquent Collection $activeOnly = $user->activePlanSubscriptions(); // rejects inactive ones ``` ``` -------------------------------- ### Renew a Subscription Source: https://github.com/laravelcm/laravel-subscriptions/blob/main/README.md Renew a subscription to set a new end date based on the plan and clear usage data. Canceled subscriptions with an ended period cannot be renewed. ```php $user->planSubscription('main')->renew(); ``` -------------------------------- ### Subscription::recordFeatureUsage() Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Records consumption of a feature associated with a subscription. It can increment usage by a default amount (1), a custom amount, or override the current usage count. For resettable features, it automatically manages the `valid_until` expiry. ```APIDOC ## `Subscription::recordFeatureUsage()` — Recording Feature Consumption Increments (or overrides) the usage counter for a feature on the subscription. Automatically manages `valid_until` expiry for resettable features. ### Usage ```php $user = User::find(1); // Default: increment by 1 $usage = $user->planSubscription('main')->recordFeatureUsage('listings'); // $usage->used => 1 // Increment by a custom amount $user->planSubscription('main')->recordFeatureUsage('listings', 3); // $usage->used => 4 // Override (not incremental) — set absolute value $user->planSubscription('main')->recordFeatureUsage('listings', 9, false); // $usage->used => 9 // For resettable features, valid_until is set automatically on first use // and refreshed when expired $user->planSubscription('main')->recordFeatureUsage('listing-duration-days'); // valid_until = subscription_created_at + 1 month ``` ``` -------------------------------- ### Subscription::reduceFeatureUsage() Source: https://context7.com/laravelcm/laravel-subscriptions/llms.txt Decrements the usage counter for a feature by a specified amount, ensuring the count does not go below zero. This is useful for actions that undo previous feature consumption. ```APIDOC ## `Subscription::reduceFeatureUsage()` — Reducing Feature Consumption Decrements the usage counter by a given amount (floors at 0). Useful when a user undoes an action (e.g., deletes a listing they had created). ### Usage ```php $user = User::find(1); // After recording 2 uses of 'deploy-sites' (total = 2): $user->planSubscription('main')->recordFeatureUsage('deploy-sites', 2); // Reduce by 1 (default) $user->planSubscription('main')->reduceFeatureUsage('deploy-sites'); // getFeatureUsage('deploy-sites') => 1 // Reduce by specific amount $user->planSubscription('main')->reduceFeatureUsage('deploy-sites', 2); // getFeatureUsage('deploy-sites') => 0 (floors at 0, never negative) ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.