PHP code example of particle-academy / laravel-catalog

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

    

particle-academy / laravel-catalog example snippets


'tables' => [
    'products'                => 'catalog_products',
    'prices'                  => 'catalog_prices',
    'product_features'        => 'catalog_product_features',
    'product_feature_configs' => 'catalog_product_feature_configs',
],

return [
    // Auto-sync products/prices to Stripe when created/updated
    'auto_sync_stripe' => env('CATALOG_AUTO_SYNC_STRIPE', false),

    // Queue connection for sync jobs
    'queue_connection' => env('CATALOG_QUEUE_CONNECTION', 'default'),

    // Broadcasting channel for sync events
    'broadcast_channel' => 'admin.products',
];

// ❌ WRONG - Product without Price
$product = Product::create(['name' => 'My Product']);
Catalog::syncProduct($product); // Will fail or create incomplete Stripe product

// ✅ CORRECT - Product with Price
$product = Product::create(['name' => 'My Product']);
Price::create([
    'product_id' => $product->id,
    'unit_amount' => 2900,
    'currency' => 'USD',
    'type' => Price::TYPE_RECURRING,
    'recurring_interval' => 'month',
]);
Catalog::syncProductAndPrices($product); // Success!

Price::create([
    'product_id' => $product->id,
    'unit_amount' => null,          // the tiers below carry it
    'currency' => 'USD',
    'type' => Price::TYPE_RECURRING,
    'recurring_interval' => 'month',
    'billing_scheme' => 'tiered',
    'tiers_mode' => 'graduated',
    'tiers' => [
        ['up_to' => 1000, 'unit_amount' => 0],   // first 1,000 

use LaravelCatalog\Facades\Catalog;
use LaravelCatalog\Models\Product;
use LaravelCatalog\Models\Price;

// Sync a product to Stripe (e at least one Price before syncing.');
}
Catalog::syncProduct($product);

// Sync a price to Stripe
$price = Price::find('price-id');
Catalog::syncPrice($price);

// Sync product and all its prices (recommended)
Catalog::syncProductAndPrices($product);

// Test Stripe connection
$result = Catalog::testConnection();
// Returns: ['success' => true, 'message' => 'Connection successful']

// Create checkout session for subscription
$checkout = Catalog::subscriptionCheckout(
    owner: $user,
    price: $price, // Must be a recurring price
    successUrl: route('subscriptions.success'),
    cancelUrl: route('subscriptions.cancel'),
    metadata: ['source' => 'admin_panel'] // Optional
);

// Create checkout session for one-time payment
$checkout = Catalog::oneTimeCheckout(
    owner: $user,
    price: $price, // Must be a one-time price
    quantity: 1,
    successUrl: route('payments.success'),
    cancelUrl: route('payments.cancel'),
    metadata: [] // Optional
);

// Get checkout URLs directly (convenience methods)
$url = Catalog::getSubscriptionCheckoutUrl($user, $price, $successUrl, $cancelUrl);
$url = Catalog::getOneTimeCheckoutUrl($user, $price, 1, $successUrl, $cancelUrl);

// Access services directly if needed
Catalog::catalogService()->testConnection();
Catalog::checkoutService()->oneTimeCheckout(...);

use LaravelCatalog\Models\Product;
use LaravelCatalog\Models\Price;

// Create a product (plan)
$product = Product::create([
    'name' => 'Pro Plan',
    'description' => 'Perfect for growing teams',
    'active' => true,
    'order' => 1,
    'metadata' => [
        'storefront' => [
            'plan' => [
                'show' => true,        // Show on storefront
                'recommended' => true,  // Mark as recommended
            ],
        ],
    ],
]);

// IMPORTANT: Create at least one Price for the Product
// Recurring monthly price (makes this a "plan")
$monthlyPrice = Price::create([
    'product_id' => $product->id,
    'unit_amount' => 2900, // $29.00 in cents
    'currency' => 'USD',
    'recurring_interval' => 'month',
    'recurring_interval_count' => 1,
    'type' => Price::TYPE_RECURRING,
    'active' => true,
]);

// You can add multiple prices to the same product
// Yearly price (same product, different billing interval)
$yearlyPrice = Price::create([
    'product_id' => $product->id,
    'unit_amount' => 29000, // $290.00 in cents (save $58/year)
    'currency' => 'USD',
    'recurring_interval' => 'year',
    'recurring_interval_count' => 1,
    'type' => Price::TYPE_RECURRING,
    'active' => true,
]);

use LaravelCatalog\Models\Price;

// Recurring monthly price (for subscription plans)
$monthlyPrice = Price::create([
    'product_id' => $product->id,
    'unit_amount' => 2900, // $29.00 in cents
    'currency' => 'USD',
    'recurring_interval' => 'month',
    'recurring_interval_count' => 1,
    'recurring_trial_period_days' => 14, // Optional trial period
    'type' => Price::TYPE_RECURRING,
    'active' => true,
]);

// Recurring yearly price
$yearlyPrice = Price::create([
    'product_id' => $product->id,
    'unit_amount' => 29000, // $290.00 in cents
    'currency' => 'USD',
    'recurring_interval' => 'year',
    'recurring_interval_count' => 1,
    'type' => Price::TYPE_RECURRING,
    'active' => true,
]);

// One-time price (for add-ons or one-time purchases)
$oneTimePrice = Price::create([
    'product_id' => $product->id,
    'unit_amount' => 9900, // $99.00 in cents
    'currency' => 'USD',
    'type' => Price::TYPE_ONE_TIME,
    'active' => true,
]);

// Using factory (recommended for tests)
$recurringPrice = Price::factory()
    ->for($product)
    ->create([
        'type' => Price::TYPE_RECURRING,
        'recurring_interval' => 'month',
    ]);

$oneTimePrice = Price::factory()
    ->for($product)
    ->oneTime()
    ->create([
        'unit_amount' => 9900,
    ]);

use LaravelCatalog\Models\Product;
use LaravelCatalog\Models\Price;

// Get all products that are plans (have recurring prices and are marked for storefront)
$plans = Product::whereHas('prices', function ($query) {
    $query->where('type', Price::TYPE_RECURRING);
})
->whereJsonContains('metadata->storefront->plan->show', true)
->with(['prices' => function ($query) {
    $query->where('type', Price::TYPE_RECURRING);
}])
->orderBy('order')
->get();

// Get the recommended plan
$recommendedPlan = Product::whereJsonContains('metadata->storefront->plan->recommended', true)
    ->with('prices')
    ->first();

// Check if a product is a plan
if ($product->isStorefrontPlan()) {
    // This is a plan shown on the storefront
}

// Get all recurring prices for a product (its plan options)
$planPrices = $product->prices()->where('type', Price::TYPE_RECURRING)->get();

use LaravelCatalog\Jobs\SyncProductToStripe;

// Dispatch sync job
SyncProductToStripe::dispatch($product->id);

// Or sync directly
use LaravelCatalog\Services\StripeCatalogService;

$catalogService = app(StripeCatalogService::class);
$catalogService->syncProduct($product);

'auto_sync_stripe' => true,

use LaravelCatalog\Facades\Catalog;
use LaravelCatalog\Models\Price;
use App\Models\User;

$user = User::find(1);
$price = Price::find($priceId);

// Ensure price has been synced to Stripe first
if (!$price->stripePriceId()) {
    Catalog::syncProductAndPrices($price->product);
}

$checkout = Catalog::subscriptionCheckout(
    owner: $user,
    price: $price,
    successUrl: route('subscriptions.success'),
    cancelUrl: route('subscriptions.cancel'),
    metadata: ['source' => 'admin_panel']
);

// Redirect to Stripe Checkout
return redirect($checkout->asStripeCheckoutSession()->url);

use LaravelCatalog\Facades\Catalog;

$checkout = Catalog::oneTimeCheckout(
    owner: $user,
    price: $oneTimePrice,
    quantity: 1,
    successUrl: route('payments.success'),
    cancelUrl: route('payments.cancel'),
);

return redirect($checkout->asStripeCheckoutSession()->url);

$order = Order::create([...]);   // your own record, still unpaid

$checkout = Catalog::oneTimeCheckout(
    owner: $user,
    price: $oneTimePrice,
    quantity: 1,
    successUrl: route('payments.success'),
    cancelUrl: route('payments.cancel'),
    metadata: ['order_id' => (string) $order->id],
);

namespace App\Listeners;

use Laravel\Cashier\Events\WebhookReceived;

class FulfilOrder
{
    public function handle(WebhookReceived $event): void
    {
        if (($event->payload['type'] ?? null) !== 'checkout.session.completed') {
            return;
        }

        $session = $event->payload['data']['object'] ?? [];

        // Check payment_status, NOT $session['status'] === 'complete'.
        // A session can be complete and still unpaid — delayed payment
        // methods clear later, and some never clear at all.
        if (($session['payment_status'] ?? null) !== 'paid') {
            return;
        }

        $orderId = $session['metadata']['order_id'] ?? null;

        if ($orderId === null) {
            return;   // Another product sold through the same Stripe account.
        }

        $order = Order::find($orderId);

        if ($order === null || $order->isPaid()) {
            return;   // Unknown, or already handled — see idempotency below.
        }

        $order->markPaid($session['id'] ?? null);
    }
}

use LaravelCatalog\Models\Product;
use LaravelCatalog\Models\Price;

// Create a product
$product = Product::factory()->create();

// Create a product with prices
$product = Product::factory()->create();
$price = Price::factory()->for($product)->create();

// Create a recurring price
$recurringPrice = Price::factory()
    ->for($product)
    ->create([
        'type' => Price::TYPE_RECURRING,
        'recurring_interval' => 'month',
    ]);

// Create a one-time price
$oneTimePrice = Price::factory()
    ->for($product)
    ->oneTime()
    ->create();



namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use LaravelCatalog\Facades\Catalog;
use LaravelCatalog\Models\Product;
use LaravelCatalog\Models\Price;

class ProductsController extends Controller
{
    public function index()
    {
        $products = Product::with('prices')
            ->orderBy('order')
            ->paginate(20);
        
        return view('admin.products.index', compact('products'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'e (ect()->route('admin.products.index')
            ->with('success', 'Product created and synced to Stripe.');
    }

    public function sync(Product $product)
    {
        // Ensure product has at least one price
        if ($product->prices->isEmpty()) {
            return redirect()->back()
                ->with('error', 'Product must have at least one Price before syncing.');
        }

        try {
            Catalog::syncProductAndPrices($product);
            return redirect()->back()
                ->with('success', 'Product synced to Stripe successfully.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Sync failed: ' . $e->getMessage());
        }
    }
}



namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use LaravelCatalog\Facades\Catalog;
use LaravelCatalog\Models\Product;
use LaravelCatalog\Models\Price;

class PlansController extends Controller
{
    public function index()
    {
        // Get all products that are plans (have recurring prices and marked for storefront)
        $plans = Product::whereHas('prices', function ($query) {
            $query->where('type', Price::TYPE_RECURRING);
        })
        ->whereJsonContains('metadata->storefront->plan->show', true)
        ->with(['prices' => function ($query) {
            $query->where('type', Price::TYPE_RECURRING);
        }])
        ->orderBy('order')
        ->get();
        
        return view('admin.plans.index', compact('plans'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'eate([
            'product_id' => $product->id,
            'unit_amount' => $validated['monthly_amount'],
            'currency' => 'USD',
            'type' => Price::TYPE_RECURRING,
            'recurring_interval' => 'month',
            'recurring_interval_count' => 1,
            'active' => true,
        ]);

        // Create yearly price if provided (optional, same product)
        if (isset($validated['yearly_amount'])) {
            Price::create([
                'product_id' => $product->id,
                'unit_amount' => $validated['yearly_amount'],
                'currency' => 'USD',
                'type' => Price::TYPE_RECURRING,
                'recurring_interval' => 'year',
                'recurring_interval_count' => 1,
                'active' => true,
            ]);
        }

        // Sync to Stripe
        Catalog::syncProductAndPrices($product);

        return redirect()->route('admin.plans.index')
            ->with('success', 'Plan created and synced to Stripe.');
    }
}



use ParticleAcademy\Fms\Facades\FMS;
use LaravelCatalog\Models\Product;

// Check if user can access a feature based on their subscription
if (FMS::canAccess('advanced-editing', $user)) {
    // User has access to advanced editing feature
}

// Get remaining quantity for resource features
$remaining = FMS::remaining('api-calls', $user);

// Check feature access in controller
public function edit(Product $product)
{
    if (!FMS::canAccess('edit-products', auth()->user())) {
        abort(403, 'You do not have permission to edit products.');
    }
    
    return view('admin.products.edit', compact('product'));
}

use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

   use LaravelCatalog\Models\Product;
   use LaravelCatalog\Models\Price;
   use LaravelCatalog\Facades\Catalog;
   
   // Create product
   $product = Product::create([
       'name' => 'Pro Plan',
       'description' => 'Perfect for growing teams',
       'active' => true,
   ]);
   
   // IMPORTANT: Create at least one Price (syncProductAndPrices($product);
   

use ParticleAcademy\Fms\Facades\FMS;
use LaravelCatalog\Models\Product;

// Check if user has access to a feature
if (FMS::canAccess('advanced-editing', $user)) {
    // User has access
}

// Get remaining quantity for resource features
$remaining = FMS::remaining('api-calls', $user);

// In your controller
use ParticleAcademy\Fms\Facades\FMS;

public function show(Product $product)
{
    // Check if user has access to this product's features
    $features = $product->productFeatures;
    
    foreach ($features as $feature) {
        if (!FMS::canAccess($feature->key, auth()->user())) {
            abort(403, "You don't have access to {$feature->name}");
        }
    }
    
    return view('products.show', compact('product'));
}

return [
    'features' => [
        'manage-products' => [
            'name' => 'Manage Products',
            'description' => 'Create, edit, and delete products',
            'type' => 'boolean',
            'enabled' => fn($user) => $user->hasRole('admin'),
        ],
        
        'product-creations' => [
            'name' => 'Product Creations',
            'description' => 'Monthly product creation limit',
            'type' => 'resource',
            'limit' => 100,
            'usage' => fn($user) => Product::where('created_by', $user->id)
                ->whereMonth('created_at', now()->month)
                ->count(),
        ],
    ],
];

use ParticleAcademy\Fms\Http\Middleware\RequireFeature;

Route::prefix('admin')->middleware([
    'auth',
    RequireFeature::class . ':manage-products'
])->group(function () {
    Route::get('/products', [ProductController::class, 'index']);
});

use Illuminate\Support\Facades\Broadcast;

Broadcast::channel(config('catalog.broadcast_channel', 'admin.products'), function ($user) {
    return $user->isAdmin(); // Adjust based on your auth logic
});

$product = Product::create([
    'name' => 'Pro Plan',
    'metadata' => ['storefront' => ['plan' => ['show' => true]]],
]);

// Monthly price
Price::create([
    'product_id' => $product->id,
    'unit_amount' => 2900,
    'currency' => 'USD',
    'type' => Price::TYPE_RECURRING,
    'recurring_interval' => 'month',
]);

// Yearly price (same product)
Price::create([
    'product_id' => $product->id,
    'unit_amount' => 29000,
    'currency' => 'USD',
    'type' => Price::TYPE_RECURRING,
    'recurring_interval' => 'year',
]);

use LaravelCatalog\Facades\Catalog;

$price = Price::find($priceId);

// Ensure price is synced before creating checkout
if (!$price->external_id) {
    Catalog::syncProductAndPrices($price->product);
    $price->refresh();
}

// Now create checkout
$checkout = Catalog::subscriptionCheckout(
    $user,
    $price,
    route('success'),
    route('cancel')
);

// Get all plans (products with recurring prices marked for storefront)
$plans = Product::whereHas('prices', function ($q) {
    $q->where('type', Price::TYPE_RECURRING);
})
->whereJsonContains('metadata->storefront->plan->show', true)
->get();

// Get all products (including one-time purchases)
$allProducts = Product::with('prices')->get();

// Get one-time products (add-ons)
$addons = Product::whereHas('prices', function ($q) {
    $q->where('type', Price::TYPE_ONE_TIME);
})
->whereJsonContains('metadata->storefront->addon->show', true)
->get();
bash
php artisan vendor:publish --tag=catalog-config
bash
php artisan migrate
bash
php artisan test tests/Feature/Catalog/

laravel-catalog/
├── src/
│   ├── Models/
│   │   ├── Product.php
│   │   ├── Price.php
│   │   └── ProductFeature.php
│   ├── Services/
│   │   ├── StripeCatalogService.php
│   │   └── StripeCheckoutService.php
│   ├── Jobs/
│   │   └── SyncProductToStripe.php
│   ├── Events/
│   │   └── ProductSyncedToStripe.php
│   ├── Facades/
│   │   └── Catalog.php
│   ├── CatalogManager.php
│   └── CatalogServiceProvider.php
├── database/
│   ├── migrations/
│   ├── factories/
│   └── seeders/
└── config/
    └── catalog.php
bash
   php artisan migrate
   
bash
   php artisan vendor:publish --tag=catalog-config