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
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);
$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'));
}
use Illuminate\Support\Facades\Broadcast;
Broadcast::channel(config('catalog.broadcast_channel', 'admin.products'), function ($user) {
return $user->isAdmin(); // Adjust based on your auth logic
});