1. Go to this page and download the library: Download openplain/laravel-flowfield 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/ */
openplain / laravel-flowfield example snippets
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Openplain\FlowField\Attributes\FlowField;
use Openplain\FlowField\Concerns\HasFlowFields;
class Customer extends Model
{
use HasFlowFields;
public function ledgerEntries()
{
return $this->hasMany(CustomerLedgerEntry::class);
}
#[FlowField(method: 'sum', relation: 'ledgerEntries', column: 'amount')]
protected function balance(): Attribute
{
return Attribute::make(get: fn () => null);
}
#[FlowField(method: 'count', relation: 'ledgerEntries')]
protected function entryCount(): Attribute
{
return Attribute::make(get: fn () => null);
}
}
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Openplain\FlowField\Concerns\InvalidatesFlowFields;
class CustomerLedgerEntry extends Model
{
use InvalidatesFlowFields;
protected array $flowFieldTargets = [
Customer::class => 'customer_id',
];
}
$customer = Customer::find(1);
// First access: computes via SQL, caches the result
$customer->balance; // 1250.75
// Second access: instant cache hit, no query
$customer->balance; // 1250.75
// Create a new entry — cache is automatically invalidated
CustomerLedgerEntry::create([
'customer_id' => 1,
'amount' => 500,
]);
// Next access: recalculates transparently
$customer->balance; // 1750.75
class OrderLine extends Model
{
use InvalidatesFlowFields;
// Map parent models to their foreign key on this table
protected array $flowFieldTargets = [
Order::class => 'order_id',
Customer::class => 'customer_id',
];
}
// Recalculate specific fields
$customer->calcFlowFields('balance', 'entry_count');
// Recalculate all FlowFields
$customer->calcFlowFields();
// Flush specific fields
$customer->flushFlowFields('balance');
// Flush all FlowFields for this record
$customer->flushFlowFields();
// Compute specific fields for all results
$customers = Customer::withFlowFields('balance', 'entry_count')->get();
// Compute all FlowFields
$customers = Customer::withFlowFields()->get();
// Highest balance first
$customers = Customer::orderByFlowField('balance', 'desc')->get();
// Combine with other conditions
$customers = Customer::where('active', true)
->orderByFlowField('entry_count', 'desc')
->paginate(25);