PHPackages                             albaroody/staging - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. albaroody/staging

ActiveLibrary[Database &amp; ORM](/categories/database)

albaroody/staging
=================

Allow any Laravel model to be saved as a draft (staged) into a separate system without affecting real database tables.

v0.1.6(5mo ago)076[4 PRs](https://github.com/albaroody/staging/pulls)MITPHPPHP ^8.2CI passing

Since Apr 29Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/albaroody/staging)[ Packagist](https://packagist.org/packages/albaroody/staging)[ Docs](https://github.com/albaroody/staging)[ GitHub Sponsors](https://github.com/:vendor_name)[ RSS](/packages/albaroody-staging/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (13)Versions (12)Used By (0)

Laravel Staging
===============

[](#laravel-staging)

[![Latest Version on Packagist](https://camo.githubusercontent.com/20ab48428ec473ff27beeb00e3fe0bc2f0be8047eaec29a9996c6e8aaaa0ce97/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f616c6261726f6f64792f73746167696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/albaroody/staging)[![GitHub Tests Action Status](https://camo.githubusercontent.com/f136c967c7bd5f330b198ba3b131939637a534cc14e9bacdd7c0ef875e7b72da/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f616c6261726f6f64792f73746167696e672f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/albaroody/staging/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/3990aad08f29778a110e97dfb529d41e8e7c50bc71007999b94f2e5874d4f8f7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f616c6261726f6f64792f73746167696e672f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/albaroody/staging/actions?query=workflow%3AFix+PHP+code+style+issues+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/9cef500035b3a433c2dd0b12569ae2ac6f1af5bef3adb86c34ac9837b88a5477/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f616c6261726f6f64792f73746167696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/albaroody/staging)

---

Laravel Staging allows you to **stage (draft)** Eloquent models and their **nested relationships** into a clean, separate system before committing them permanently to your main database.

- Stage parent models like `Patient`, `Post`, `Order`, etc.
- Stage related models like `Sales`, `Items`, `Comments`, etc.
- Hydrate full Eloquent models from staged data (not just arrays)
- Promote staged data to production tables cleanly
- Keep your main database structure untouched — no intrusive columns added!

Perfect for multi-step forms, draft publishing systems, and modular deferred saving workflows.

---

Installation
------------

[](#installation)

You can install the package via Composer:

```
composer require albaroody/staging
```

You can publish and run the staging migration with

```
php artisan vendor:publish --tag="staging-migrations"
php artisan migrate
```

You can publish the config file with:

```
php artisan vendor:publish --tag="staging-config"
```

Usage
-----

[](#usage)

1. Add the Stagable trait to your model:

```
use Albaroody\\Staging\\Traits\\Stagable;

class Patient extends Model
{
    use Stagable;
}
```

2. Stage a model:

```
// 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',
]);
```

3. Load a staged model:

```
$stagedPatient = Patient::findStaged($stagingId);

// Now you can use it like a normal model
echo $stagedPatient->name;
```

4. Promote a staged model to the database:

```
$realPatient = $stagedPatient->promoteFromStaging();

// The staging entry is automatically deleted after promotion
```

HasMany Relationships
---------------------

[](#hasmany-relationships)

The library supports staging `hasMany` relationships, allowing you to create multiple child records before saving the parent.

### Basic Usage

[](#basic-usage)

1. **Stage multiple children at once:**

```
$stockLevels = [
    ['quantity' => 100, 'location' => 'Warehouse A', '_sort_order' => 0],
    ['quantity' => 50, 'location' => 'Warehouse B', '_sort_order' => 1],
];

$stagingIds = StockLevel::stageMany($stockLevels);
```

2. **Link staged children to a parent:**

```
// 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);
```

3. **Find staged children by parent:**

```
$stagedChildren = StockLevel::findStagedChildren($productStagingId, Product::class);

foreach ($stagedChildren as $child) {
    echo $child['data']['location']; // 'Warehouse A', 'Warehouse B'
}
```

4. **Save staged children when parent is saved:**

```
// 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
);
```

### Automatic Child Saving

[](#automatic-child-saving)

You can configure models to automatically save staged children when the parent is created via HTTP request:

1. **Define hasMany relationships in your model:**

```
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',
            ],
        ];
    }
}
```

2. **Create parent via HTTP request with staging IDs in the request:**

```
// 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;
}
```

**Note:** The automatic child saving works by checking the request for `_staging_id` and `{relationship_name}_staging_ids` keys. These keys must be present in the request when creating the parent model.

### Get Staged Collection for Display

[](#get-staged-collection-for-display)

Get a collection of staged objects for display in forms or tables:

```
$stagingIds = StockLevel::stageMany([
    ['quantity' => 100, 'location' => 'Warehouse A'],
    ['quantity' => 50, 'location' => 'Warehouse B'],
]);

$collection = StockLevel::getStagedCollection($stagingIds);

// Use like Eloquent models
foreach ($collection as $item) {
    echo $item->location; // 'Warehouse A', 'Warehouse B'
    echo $item->is_staged; // true
}
```

### Staging Endpoints (Optional)

[](#staging-endpoints-optional)

You can use the included Route macro to easily add staging endpoints to your controllers:

```
// In routes/web.php or routes/api.php
use Illuminate\Support\Facades\Route;

Route::resourceWithStage('products', ProductController::class);
```

This will create:

- `POST /products/stage` - Stage a product (in addition to standard resource routes)
- All standard resource routes (`GET /products`, `POST /products`, etc.)

Your controller should implement a `stage` method:

```
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function stage(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|string',
            'price' => 'required|numeric',
        ]);

        $product = new Product($validatedData);
        $stagingId = $product->stage();

        return response()->json([
            'message' => 'Product staged successfully.',
            'staging_id' => $stagingId,
        ]);
    }
}
```

**Note:** Your `Product` model must use the `Stagable` trait for the `stage()` method to be available.

### Storing References to Staged Models

[](#storing-references-to-staged-models)

You can store references to staged models in your attributes (useful for belongsTo relationships):

```
// Stage supplier first
$supplierStagingId = Supplier::stageNew(['name' => 'Acme Corp']);

// Stage product with reference to staged supplier
$productStagingId = Product::stageNew([
    'name' => 'Widget',
    'supplier_staging_id' => $supplierStagingId, // Store reference
]);

// Later, when promoting, you'll need to handle the relationship manually:
$stagedProduct = Product::findStaged($productStagingId);
$stagedSupplier = Supplier::findStaged($stagedProduct->supplier_staging_id);

$realSupplier = $stagedSupplier->promoteFromStaging();
$stagedProduct->supplier_id = $realSupplier->id; // Set actual foreign key
$realProduct = $stagedProduct->promoteFromStaging();
```

Features
--------

[](#features)

✅ Stage any Eloquent model as a draft
✅ Stage multiple children at once with `stageMany()`
✅ Link staged children to staged parents
✅ Automatic saving of hasMany children when parent is created
✅ Preserve sort order for staged items
✅ Get staged collections for display (model-like objects)
✅ Clean promotion to production tables
✅ No intrusive columns in your main tables

Enjoy easy staging without cluttering your main table with extra columns!

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Albaroody](https://github.com/Albaroody)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance83

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 71.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~35 days

Recently: every ~52 days

Total

7

Last Release

166d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5408efc8eba9cc1b739f2d8efecc0e0c1e06841df09bd1b2c5178623c6aeffd8?d=identicon)[albaroody](/maintainers/albaroody)

---

Top Contributors

[![albaroody](https://avatars.githubusercontent.com/u/19997163?v=4)](https://github.com/albaroody "albaroody (15 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (3 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (3 commits)")

---

Tags

laravelstagingalbaroody

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/albaroody-staging/health.svg)

```
[![Health](https://phpackages.com/badges/albaroody-staging/health.svg)](https://phpackages.com/packages/albaroody-staging)
```

###  Alternatives

[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[spatie/laravel-model-flags

Add flags to Eloquent models

4301.1M1](/packages/spatie-laravel-model-flags)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)[spatie/laravel-sql-commenter

Add comments to SQL queries made by Laravel

1931.4M1](/packages/spatie-laravel-sql-commenter)[spatie/laravel-deleted-models

Automatically copy deleted records to a separate table

409109.8k4](/packages/spatie-laravel-deleted-models)[wnx/laravel-backup-restore

A package to restore database backups made with spatie/laravel-backup.

203330.1k2](/packages/wnx-laravel-backup-restore)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
