Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Filament Saas Laravel Package

a2insights/filament-saas

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**: Require the package via Composer:
   ```bash
   composer require a2insights/filament-saas
  1. Publish Config: Publish the default configuration and migration files:
    php artisan vendor:publish --provider="A2Insights\FilamentSaas\FilamentSaasServiceProvider" --tag="filament-saas-config"
    php artisan vendor:publish --provider="A2Insights\FilamentSaas\FilamentSaasServiceProvider" --tag="filament-saas-migrations"
    
  2. Run Migrations: Execute the migrations to set up the required tables:
    php artisan migrate
    
  3. Register Plugin: Add the plugin to your Filament admin panel in app/Providers/Filament/AdminPanelProvider.php:
    public function panel(Panel $panel): Panel
    {
        return $panel
            ->plugins([
                \A2Insights\FilamentSaas\FilamentSaasPlugin::make(),
            ]);
    }
    

First Use Case: Creating a Subscription Plan

To define a subscription plan, use the createPlan method in a seeder or migration:

use A2Insights\FilamentSaas\Models\Plan;

Plan::create([
    'name' => 'Premium',
    'description' => 'Access to all features',
    'price' => 29.99,
    'interval' => 'month',
    'interval_count' => 1,
    'trial_days' => 7,
]);

Implementation Patterns

Core Workflows

  1. Plan Management:

    • Use the Plan model to define subscription tiers (e.g., Free, Basic, Premium).
    • Leverage the Filament admin panel to manage plans via the built-in resource:
      use A2Insights\FilamentSaas\Resources\PlanResource;
      
    • Example: Dynamically fetch plans in a policy or service:
      $plans = \A2Insights\FilamentSaas\Models\Plan::active()->get();
      
  2. Subscription Handling:

    • Attach subscriptions to users via the Subscription model:
      $user->subscriptions()->create([
          'plan_id' => $plan->id,
          'ends_at' => now()->addMonths($plan->interval_count),
      ]);
      
    • Use the Subscription model to check active subscriptions:
      if ($user->subscriptions()->active()->exists()) {
          // User is subscribed
      }
      
  3. Billing Integration:

    • Extend the package to integrate with Stripe or other payment gateways by overriding the BillingService:
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->bind(\A2Insights\FilamentSaas\Contracts\BillingService::class, \App\Services\CustomStripeService::class);
      }
      
  4. Webhook Handling:

    • Listen to subscription events (e.g., subscription.created, subscription.cancelled) using Laravel events:
      event(new \A2Insights\FilamentSaas\Events\SubscriptionCreated($subscription));
      
    • Register listeners in EventServiceProvider:
      protected $listen = [
          \A2Insights\FilamentSaas\Events\SubscriptionCreated::class => [
              \App\Listeners\HandleSubscriptionCreated::class,
          ],
      ];
      
  5. User Access Control:

    • Gate access to features based on subscription status:
      public function authorize(AuthorizesRequests $request)
      {
          return $request->user()->subscriptions()->active()->where('plan_id', $premiumPlanId)->exists();
      }
      

Integration Tips

  • Filament Widgets: Use the provided widgets (e.g., RevenueChart) to display SaaS metrics in your dashboard:
    public function getWidgets(): array
    {
        return [
            \A2Insights\FilamentSaas\Widgets\RevenueChart::class,
        ];
    }
    
  • Localization: Override translations in resources/lang/vendor/filament-saas for multi-language support.
  • Testing: Use the createTestPlan() and createTestSubscription() helper methods in tests:
    $plan = \A2Insights\FilamentSaas\Models\Plan::createTestPlan();
    $user->createTestSubscription($plan);
    

Gotchas and Tips

Pitfalls

  1. Migration Conflicts:

    • Ensure the package’s migrations don’t conflict with existing users or subscriptions tables. Customize the migration paths if needed:
      // config/filament-saas.php
      'migration_paths' => [
          'custom' => database_path('migrations'),
      ],
      
    • Run php artisan vendor:publish --tag="filament-saas-migrations" again to republish with custom paths.
  2. Plan Activation Logic:

    • The active() scope on the Plan model checks for is_active and starts_at/ends_at dates. Ensure these fields are correctly populated:
      // Avoid this:
      Plan::create(['is_active' => false]); // Will not appear in active() scope
      
  3. Subscription Overlaps:

    • The package assumes non-overlapping subscriptions. If a user can have multiple active subscriptions (e.g., team plans), override the Subscription model’s active() scope:
      public function scopeActive($query)
      {
          return $query->whereNull('ends_at')->orWhere('ends_at', '>', now());
      }
      
  4. Webhook Idempotency:

    • Payment gateway webhooks may fire multiple times. Use Laravel’s ignoreMissing or idempotency keys in your event handlers:
      public function handle(SubscriptionCreated $event)
      {
          if (cache()->has("subscription.{$event->subscription->id}.created")) {
              return;
          }
          // Process subscription
          cache()->put("subscription.{$event->subscription->id}.created", true, now()->addHours(1));
      }
      
  5. Filament Plugin Registration:

    • If the plugin doesn’t appear in Filament, ensure:
      • The FilamentSaasServiceProvider is registered in config/app.php.
      • The plugin is added after the Filament\Panel is instantiated in AdminPanelProvider.

Debugging

  • Log Subscription Events: Enable debug logging for subscription events in config/filament-saas.php:

    'debug' => env('SAAS_DEBUG', false),
    

    Check logs at storage/logs/laravel.log for event payloads.

  • Test Webhooks Locally: Use Laravel’s queue:work to process webhooks in real-time:

    php artisan queue:work --once
    

    Simulate webhooks with:

    \A2Insights\FilamentSaas\Events\SubscriptionCreated::dispatch($subscription);
    

Extension Points

  1. Custom Fields: Add custom fields to the Plan or Subscription models by extending them:

    // app/Models/Plan.php
    class Plan extends \A2Insights\FilamentSaas\Models\Plan
    {
        protected $casts = [
            'features' => 'array',
        ];
    }
    

    Update the Filament resource to reflect these changes.

  2. Custom Billing Logic: Override the BillingService to implement custom logic (e.g., coupons, prorations):

    namespace App\Services;
    
    use A2Insights\FilamentSaas\Contracts\BillingService as BaseBillingService;
    
    class CustomBillingService implements BaseBillingService
    {
        public function createSubscription($user, $plan, $data)
        {
            // Custom logic here
            return $subscription;
        }
    }
    
  3. API Endpoints: Expose SaaS data via API using Laravel’s Route::apiResource:

    Route::apiResource('plans', \A2Insights\FilamentSaas\Http\Controllers\PlanController::class);
    

    Extend the controller to add custom logic.

  4. Notifications: Customize subscription notifications by extending the SubscriptionCreated event:

    use A2Insights\FilamentSaas\Events\SubscriptionCreated;
    
    class CustomSubscriptionCreated implements ShouldBroadcast
    {
        public function __construct(public $subscription) {}
    
        public function broadcastOn()
        {
            return new Channel('subscriptions');
        }
    }
    
  5. Testing: Use the package’s test helpers to mock subscriptions in PHPUnit:

    $user = User::factory()->create();
    $plan = \A2Insights\FilamentSaas\Models\Plan::createTestPlan();
    $user->createTestSubscription($plan, now()->addDays(30));
    

    Verify subscription status:

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui