PHP code example of centrex / laravel-btyd

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

    

centrex / laravel-btyd example snippets


use Centrex\Btyd\Btyd;

// Each transaction: ['date' => Carbon|string, 'amount' => float]
$transactions = [
    ['date' => '2024-01-15', 'amount' => 120.00],
    ['date' => '2024-03-02', 'amount' => 85.50],
    ['date' => '2024-06-18', 'amount' => 200.00],
];

$summary = Btyd::transactionsToSummary($transactions);
// returns: frequency, recency (days), T (days since first purchase), monetary, n_transactions, total_revenue

$btyd = new Btyd();

// Fit BG/NBD on cohort summaries (frequency, recency, T lpha' => ..., 'a' => ..., 'b' => ...]

// Fit Gamma-Gamma on customers with at least 1 repeat purchase (frequency, monetary 

// Expected number of transactions over the next 12 months
$expectedTx = $btyd->expectedTransactions($customerSummary, horizonMonths: 12);

// Expected monetary value per transaction
$expectedMonetary = $btyd->expectedMonetary($customerSummary);

// Customer lifetime value (expectedTx × expectedMonetary)
$clv = $btyd->customerClv($customerSummary, horizonMonths: 12);

use Centrex\Btyd\Models\BtydParam;

// Save fitted params for a given model class
BtydParam::updateOrCreate(
    ['model' => App\Models\Customer::class],
    ['params' => array_merge($bgnbdParams, $ggParams)],
);

// Load later
$params = BtydParam::getParams(App\Models\Customer::class);

$btyd = new Btyd();

// Build summaries for all customers
$summaries = Customer::all()->map(fn ($c) =>
    Btyd::transactionsToSummary($c->orders->map(fn ($o) => [
        'date' => $o->created_at,
        'amount' => $o->total,
    ])->toArray())
)->toArray();

// Fit
$btyd->fitBgNbd($summaries);
$btyd->fitGammaGamma($summaries);

// Predict CLV for a single customer
$clv = $btyd->customerClv($summaries[0], 12);
echo "12-month CLV: {$clv}";
bash
composer vendor:publish --tag="laravel-btyd-migrations"
php artisan migrate