You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Laravel构建多版本Web应用的实现方案咨询

How to Implement Free & Business Tiers in Laravel Without Duplicating Code

Hey there! I’ve built a few Laravel apps with free/business tiers before, so I totally get wanting to avoid maintaining two separate codebases—what a headache that would be. Here are the most practical, low-fuss ways to pull this off efficiently:

1. Feature Flagging (The Go-To Approach)

This is the simplest and most scalable method. You’ll define "flags" for each premium feature, then check those flags throughout your app to show/hide functionality based on the user’s plan.

Step 1: Define Your Features

Create a config file to list all premium features, or store them in your database if you want to toggle features dynamically:

// config/features.php
return [
    'advanced_reporting' => true, // Mark as enabled for business plans
    'team_collaboration' => true,
    'priority_support' => true,
];

Step 2: Build a Helper Function

Make a reusable helper to check if the current user can access a feature:

// app/helpers.php (don't forget to autoload this in composer.json)
function hasPremiumFeature(string $feature): bool
{
    // For guests, default to false
    if (!auth()->check()) {
        return false;
    }

    // Check if the user is on a business plan AND the feature is enabled
    return auth()->user()->plan === 'business' && config("features.{$feature}");
}

Step 3: Use the Flag Everywhere

In Blade views:

@if(hasPremiumFeature('advanced_reporting'))
    <a href="/dashboard/reports/advanced" class="btn btn-primary">View Advanced Reports</a>
@else
    <div class="alert alert-info">
        Advanced Reports are included in our <strong>Business Plan</strong>. <a href="/pricing">Upgrade now</a>!
    </div>
@endif

In controllers:

public function generateAdvancedReport()
{
    if (!hasPremiumFeature('advanced_reporting')) {
        abort(403, 'This feature is only available to Business Plan users.');
    }

    // Your report generation logic here
}

2. Plan-Based Authorization with Gates/Policies

Laravel’s built-in authorization system is perfect for controlling access to premium routes, actions, or resources.

Define a Gate

Add this to your AuthServiceProvider:

// app/Providers/AuthServiceProvider.php
public function boot()
{
    $this->registerPolicies();

    Gate::define('use-business-features', function ($user) {
        return $user->plan === 'business';
    });
}

Use the Gate in Your App

In controllers:

public function manageTeam()
{
    $this->authorize('use-business-features');

    // Team management logic
}

In Blade:

@can('use-business-features')
    <nav class="sidebar">
        <a href="/team">Manage Team</a>
        <!-- Other business-only links -->
    </nav>
@endcan

You can even create more granular gates for specific features if needed (e.g., access-advanced-reports instead of a broad business gate).

3. Modular Feature Services (For Larger Apps)

If your business tier has a lot of complex features, you can encapsulate them into dedicated services and load them conditionally.

Create Feature Services

// app/Services/FreeFeatures.php
class FreeFeatures
{
    public function getStorageLimit(): int
    {
        return 100; // GB
    }
}

// app/Services/BusinessFeatures.php
class BusinessFeatures extends FreeFeatures
{
    public function getStorageLimit(): int
    {
        return 1000; // GB
    }

    public function generateAdvancedReport()
    {
        // Complex report logic
    }
}

Bind the Service Conditionally

In your AppServiceProvider:

public function register()
{
    $this->app->bind(FeatureService::class, function ($app) {
        if ($app->auth->check() && $app->auth->user()->plan === 'business') {
            return new BusinessFeatures();
        }

        return new FreeFeatures();
    });
}

Then inject the service wherever you need it:

public function showStorageUsage(FeatureService $features)
{
    $limit = $features->getStorageLimit();
    // Display usage info
}

Pro Tips to Keep Code Clean

  • Use Traits: Extract repeated plan-checking logic into traits (e.g., HasPlanAccess) and apply them to your models/controllers.
  • Conditional View Components: Create Blade components that render different content based on the user’s plan (e.g., <x-feature-card :feature="advanced_reporting"/>).
  • Database Defaults: Set plan-specific defaults in your models (e.g., $user->storage_limit returns different values based on $user->plan).

All these methods let you keep a single codebase while seamlessly supporting both free and business tiers. Start with feature flags and gates—they’re easy to implement and scale as your app grows!

内容的提问来源于stack exchange,提问作者Osuwariboy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:01:47