1. Go to this page and download the library: Download albaroody/staging 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/ */
albaroody / staging example snippets
use Albaroody\\Staging\\Traits\\Stagable;
class Patient extends Model
{
use Stagable;
}
// Option 1: Stage an existing model instance
$patient = new Patient([
'name' => 'John Doe',
]);
$stagingId = $patient->stage();
// Option 2: Stage a new model using static method
$stagingId = Patient::stageNew([
'name' => 'John Doe',
]);
$stagedPatient = Patient::findStaged($stagingId);
// Now you can use it like a normal model
echo $stagedPatient->name;
$realPatient = $stagedPatient->promoteFromStaging();
// The staging entry is automatically deleted after promotion
// Stage the parent first
$product = new Product(['name' => 'Widget', 'price' => 10.00]);
$productStagingId = $product->stage();
// Link staged children to parent
StockLevel::linkStagedToParent($stagingIds, $productStagingId, Product::class);
$stagedChildren = StockLevel::findStagedChildren($productStagingId, Product::class);
foreach ($stagedChildren as $child) {
echo $child['data']['location']; // 'Warehouse A', 'Warehouse B'
}
// Save the parent
$realProduct = $product->promoteFromStaging();
// Save all staged children with the parent's ID
$createdIds = StockLevel::saveStagedChildren(
$realProduct->id,
$productStagingId,
Product::class,
'product_id' // foreign key column name
);
use Albaroody\Staging\Traits\Stagable;
class Product extends Model
{
use Stagable;
protected static function getHasManyRelationships(): array
{
return [
'stock_levels' => [
'model' => StockLevel::class,
'foreign_key' => 'product_id',
],
];
}
}
// In your controller's store method
public function store(Request $request)
{
// Stage children first (if coming from form)
$stockLevelIds = StockLevel::stageMany([
['quantity' => 100, 'location' => 'Warehouse A'],
['quantity' => 50, 'location' => 'Warehouse B'],
]);
// Stage parent
$product = new Product($request->only(['name', 'price']));
$productStagingId = $product->stage();
// Link children
StockLevel::linkStagedToParent($stockLevelIds, $productStagingId, Product::class);
// Create product - staging IDs must be in the request for automatic saving
$product = Product::create($request->only(['name', 'price']) + [
'_staging_id' => $productStagingId,
'stock_levels_staging_ids' => $stockLevelIds,
]);
// Children are automatically saved with product_id set!
return $product;
}