PHP code example of masterix21 / laravel-subscriptions

1. Go to this page and download the library: Download masterix21/laravel-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/ */

    

masterix21 / laravel-subscriptions example snippets


// 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();
    }
}

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,
    ],
];

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,
]);

Plan::active()->get();    // enabled = true
Plan::inactive()->get();  // enabled = false
Plan::visible()->get();   // hidden = false
Plan::invisible()->get(); // hidden = true

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]);

// 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',
    ]
);

$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

// 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']));

// 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);

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 

'stripe' => [
    'secret' => env('STRIPE_SECRET'),
    'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
],

$plan->meta['stripe_id'] = 'price_xxx';
$plan->save();

use LucaLongo\Subscriptions\Payments\Gateways\StripeGateway;

return app(StripeGateway::class)->subscribe(
    plan: $plan,
    subscriber: $user,
    successUrl: route('subscription.success'),
    cancelUrl: route('subscription.cancel'),
);

// app/Models/Plan.php
class Plan extends \LucaLongo\Subscriptions\Models\Plan
{
    // Your customizations
}

// config/subscriptions.php
'models' => [
    'plan' => \App\Models\Plan::class,
    // ...
],
bash
php artisan vendor:publish --tag="laravel-subscriptions-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="laravel-subscriptions-config"
bash
php artisan vendor:publish --tag="laravel-subscriptions-views"