masterix21 / laravel-subscriptions
Laravel subscriptions for an unopinionated payment system
Package info
github.com/masterix21/laravel-subscriptions
pkg:composer/masterix21/laravel-subscriptions
Fund package maintenance!
Requires
- php: ^8.2|^8.3|^8.4
- illuminate/contracts: ^12.0|^13.0
- spatie/laravel-collection-macros: ^8.0
- spatie/laravel-package-tools: ^1.19
- stripe/stripe-php: ^20.0
Requires (Dev)
- filament/tables: ^4.0|^5.0
- larastan/larastan: ^3.1
- laravel/pint: ^1.21
- nunomaduro/collision: ^8.6|^9.0
- orchestra/testbench: ^10.0|^11.0
- pestphp/pest: ^3.7|^4.4
- pestphp/pest-plugin-arch: ^3.0|^4.0
- pestphp/pest-plugin-laravel: ^3.1|^4.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-phpunit: ^2.0
- spatie/laravel-ray: ^1.39
README
A flexible, payment-agnostic subscription system for Laravel. Manage plans, features, trials, grace periods, and recurring billing with built-in Stripe support and Livewire admin views.
Requirements
- PHP 8.2+
- Laravel 12 or 13
Installation
composer require masterix21/laravel-subscriptions
Publish and run the migrations:
php artisan vendor:publish --tag="laravel-subscriptions-migrations"
php artisan migrate
Publish the config file:
php artisan vendor:publish --tag="laravel-subscriptions-config"
Setup
Prepare your Subscriber model
Your subscriber model (typically User) must implement SubscriberContract and use the HasSubscriptions trait.
The model also needs a meta JSON field for storing payment gateway data:
// Migration $table->json('meta')->nullable();
use Illuminate\Database\Eloquent\Casts\AsArrayObject; use LucaLongo\Subscriptions\Models\Concerns\HasSubscriptions; use LucaLongo\Subscriptions\Models\Contracts\SubscriberContract; class User extends Authenticatable implements SubscriberContract { use HasSubscriptions; protected $fillable = [ // ... 'meta', ]; protected function casts(): array { return [ 'meta' => AsArrayObject::class, ]; } public function customerName(): string { return $this->name; } public function customerEmail(): string { return $this->email; } public function customerUniqueIdentifierKey(): string { return $this->getKeyName(); } public function customerUniqueIdentifier(): string { return (string) $this->getKey(); } }
Configuration
The config file (config/subscriptions.php) allows you to customize the subscriber model, payment gateway, and all model classes:
return [ 'subscriber' => \App\Models\User::class, 'payment_gateway' => \LucaLongo\Subscriptions\Payments\Gateways\StripeGateway::class, 'models' => [ 'plan' => \LucaLongo\Subscriptions\Models\Plan::class, 'feature' => \LucaLongo\Subscriptions\Models\Feature::class, 'plan_feature' => \LucaLongo\Subscriptions\Models\PlanFeature::class, 'subscription' => \LucaLongo\Subscriptions\Models\Subscription::class, ], ];
Usage
Creating Plans
use LucaLongo\Subscriptions\Models\Plan; use LucaLongo\Subscriptions\Enums\DurationInterval; $plan = Plan::create([ 'name' => 'Pro Monthly', 'description' => 'Pro plan, billed monthly', 'duration_period' => 1, 'duration_interval' => DurationInterval::MONTH, 'price' => 9.99, 'trial_period' => 14, 'trial_interval' => DurationInterval::DAY, 'grace_period' => 3, 'grace_interval' => DurationInterval::DAY, ]);
The code field is auto-generated from the name (e.g. pro-monthly).
Plan scopes
Plan::active()->get(); // enabled = true Plan::inactive()->get(); // enabled = false Plan::visible()->get(); // hidden = false Plan::invisible()->get(); // hidden = true
Managing Features
use LucaLongo\Subscriptions\Models\Feature; $feature = Feature::create(['name' => 'API Access']); // Attach features to a plan (with optional max usage) $plan->features()->attach($feature, ['max_usage' => 1000]);
Subscribing
// From the plan $subscription = $plan->subscribe($user); // From the user $subscription = $user->subscribe($plan); // With options $subscription = $plan->subscribe( subscriber: $user, status: SubscriptionStatus::TRIALING, autoRenew: false, data: [ 'next_billing_at' => now()->addMonths(2), 'payment_provider' => 'stripe', 'payment_provider_reference' => 'sub_xxx', ] );
Checking Subscription State
$subscription->isActive(); // Currently active (or in grace period) $subscription->onTrial(); // In trial period $subscription->onGrace(); // In grace period $subscription->isRevoked(); // Permanently revoked $subscription->isRevokable(); // Can be revoked
Checking Features
// On the subscriber $user->hasActiveFeature('api-access'); $user->hasAnyActiveFeatures(['api-access', 'export']); $user->hasAllActiveFeatures(['api-access', 'export']); $user->subscribedTo('pro-monthly'); // by code $user->subscribedTo($plan); // by model // On the subscription $subscription->hasFeature('api-access'); $subscription->hasAnyFeature(collect(['api-access', 'export'])); $subscription->hasAllFeature(collect(['api-access', 'export']));
Managing Subscriptions
// Cancel (ends at next billing date by default) $subscription->cancel(); $subscription->cancel(now()->addDays(7)); // custom end date // Renew $subscription->renew(); $subscription->renew(now()->addMonths(3)); // custom next billing date // Revoke (permanent, cannot be renewed) $subscription->revoke(); // Auto-renewal app(DisableAutoRenewSubscription::class)->execute($subscription); app(EnableAutoRenewSubscription::class)->execute($subscription);
Middleware
Three middleware are available to protect routes based on subscription features:
use LucaLongo\Subscriptions\Http\Middleware\RequiresFeatureMiddleware; use LucaLongo\Subscriptions\Http\Middleware\RequiresAnyFeaturesMiddleware; use LucaLongo\Subscriptions\Http\Middleware\RequiresAllFeaturesMiddleware; // Single feature Route::middleware(RequiresFeatureMiddleware::class . ':api-access') ->get('/api/data', DataController::class); // Any of multiple features (comma, pipe, or space separated) Route::middleware(RequiresAnyFeaturesMiddleware::class . ':export,api-access') ->get('/tools', ToolsController::class); // All features required Route::middleware(RequiresAllFeaturesMiddleware::class . ':export,api-access') ->get('/advanced', AdvancedController::class);
All middleware return a 403 response if the user doesn't meet the requirements.
Stripe Integration
Setup
Add your Stripe credentials to config/services.php:
'stripe' => [ 'secret' => env('STRIPE_SECRET'), 'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'), ],
Store the Stripe Price ID in the plan's meta field:
$plan->meta['stripe_id'] = 'price_xxx'; $plan->save();
Creating a Checkout Session
use LucaLongo\Subscriptions\Payments\Gateways\StripeGateway; return app(StripeGateway::class)->subscribe( plan: $plan, subscriber: $user, successUrl: route('subscription.success'), cancelUrl: route('subscription.cancel'), );
This redirects the user to Stripe Checkout. The webhook handler automatically syncs subscription state back to your database.
Webhook
The package registers a webhook route at POST /hooks/payments/stripe. The handler processes these Stripe events:
customer.subscription.createdcustomer.subscription.updatedcustomer.subscription.deletedcustomer.deleted
Livewire Admin Views
The package includes optional Livewire components for managing plans, features, and subscriptions using Filament Table Builder.
Install the required dependencies:
composer require livewire/volt filament/tables guava/filament-clusters
Publish the views:
php artisan vendor:publish --tag="laravel-subscriptions-views"
Available components:
<livewire:subscriptions::manage-plans /> <livewire:subscriptions::manage-features /> <livewire:subscriptions::manage-subscriptions :subscriber="$user" />
Extending Models
You can extend any model by creating your own class and updating the config:
// app/Models/Plan.php class Plan extends \LucaLongo\Subscriptions\Models\Plan { // Your customizations } // config/subscriptions.php 'models' => [ 'plan' => \App\Models\Plan::class, // ... ],
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.