PHPackages                             bensedev/request-bag - 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. [PSR &amp; Standards](/categories/psr-standards)
4. /
5. bensedev/request-bag

ActiveLibrary[PSR &amp; Standards](/categories/psr-standards)

bensedev/request-bag
====================

Request-scoped data container for Laravel

v1.0.1(7mo ago)00[2 PRs](https://github.com/BenSeDev/laravel-request-bag/pulls)MITPHPPHP ^8.4CI passing

Since Oct 6Pushed 5mo agoCompare

[ Source](https://github.com/BenSeDev/laravel-request-bag)[ Packagist](https://packagist.org/packages/bensedev/request-bag)[ RSS](/packages/bensedev-request-bag/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (8)Versions (5)Used By (0)

RequestBag
==========

[](#requestbag)

**A simple, request-scoped data container for Laravel**

RequestBag provides an easy way to share data between classes during a single request lifecycle without passing parameters around. Perfect for middleware chains, Inertia.js setups, and any scenario where you need to share contextual data across your application.

Why RequestBag?
---------------

[](#why-requestbag)

- 🎯 **Request-scoped** - Data lives only for the duration of a single request
- 🚀 **No parameter passing** - Share data between classes without cluttering method signatures
- 🔒 **Type-safe** - Built with PHP 8.4+ and strict types
- 🎨 **Clean API** - Simple, intuitive methods that just work
- 🧪 **Fully tested** - Comprehensive test coverage with Pest
- ✨ **Laravel-friendly** - Facade support and automatic service provider registration

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

[](#installation)

Install via Composer:

```
composer require bensedev/request-bag
```

The service provider and facade are automatically registered via Laravel's package discovery.

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

```
use Bensedev\RequestBag\Facades\RequestBag;

// Add data
RequestBag::add('user_permissions', ['edit', 'delete', 'create']);
RequestBag::add('tenant_id', 123);

// Retrieve data
$permissions = RequestBag::get('user_permissions');
$tenantId = RequestBag::get('tenant_id');

// With default value
$theme = RequestBag::get('theme', 'light');

// Check if key exists and has value
if (RequestBag::has('user_permissions')) {
    // Key exists and is not empty
}

// Check if key exists (even if empty)
if (RequestBag::exists('theme')) {
    // Key exists
}
```

### Middleware Example

[](#middleware-example)

Share computed data from middleware with your controllers:

```
namespace App\Http\Middleware;

use Bensedev\RequestBag\Facades\RequestBag;
use Closure;

class LoadUserPermissions
{
    public function handle($request, Closure $next)
    {
        $permissions = auth()->user()->permissions->pluck('name')->toArray();

        // Store in RequestBag instead of adding to request
        RequestBag::add('user_permissions', $permissions);
        RequestBag::add('is_admin', auth()->user()->isAdmin());

        return $next($request);
    }
}
```

Then access it anywhere in your application:

```
namespace App\Http\Controllers;

use Bensedev\RequestBag\Facades\RequestBag;

class PostController extends Controller
{
    public function store()
    {
        // No need to pass permissions around!
        if (RequestBag::has('user_permissions')) {
            $permissions = RequestBag::get('user_permissions');

            if (in_array('create_post', $permissions)) {
                // Create post
            }
        }
    }
}
```

### Inertia.js Example

[](#inertiajs-example)

Share data with your Inertia frontend:

```
namespace App\Http\Middleware;

use Bensedev\RequestBag\Facades\RequestBag;
use Illuminate\Http\Request;
use Inertia\Middleware;

class HandleInertiaRequests extends Middleware
{
    public function share(Request $request): array
    {
        return array_merge(parent::share($request), [
            'auth' => [
                'user' => $request->user(),
                // Pull from RequestBag populated earlier in middleware chain
                'permissions' => RequestBag::get('user_permissions', []),
                'is_admin' => RequestBag::get('is_admin', false),
            ],
            'tenant' => [
                'id' => RequestBag::get('tenant_id'),
                'name' => RequestBag::get('tenant_name'),
            ],
        ]);
    }
}
```

### Service/Repository Pattern

[](#servicerepository-pattern)

Share computed data between services:

```
namespace App\Services;

use Bensedev\RequestBag\Facades\RequestBag;

class TenantService
{
    public function loadTenantContext(int $tenantId): void
    {
        $tenant = Tenant::with('settings')->find($tenantId);

        RequestBag::merge([
            'tenant_id' => $tenant->id,
            'tenant_name' => $tenant->name,
            'tenant_settings' => $tenant->settings->toArray(),
        ]);
    }
}

class InvoiceService
{
    public function createInvoice(array $data): Invoice
    {
        // Access tenant data without dependency injection
        $tenantId = RequestBag::get('tenant_id');
        $settings = RequestBag::get('tenant_settings');

        return Invoice::create([
            'tenant_id' => $tenantId,
            'currency' => $settings['default_currency'],
            // ...
        ]);
    }
}
```

API Reference
-------------

[](#api-reference)

### Adding Data

[](#adding-data)

```
// Add a single value
RequestBag::add(string $key, mixed $value): self

// Merge multiple values
RequestBag::merge(array $data): self

// Example
RequestBag::add('user_id', 123);
RequestBag::merge(['theme' => 'dark', 'locale' => 'en']);
```

### Retrieving Data

[](#retrieving-data)

```
// Get a value (with optional default)
RequestBag::get(string $key, mixed $default = null): mixed

// Get all data
RequestBag::all(): array

// Example
$userId = RequestBag::get('user_id');
$theme = RequestBag::get('theme', 'light');
$all = RequestBag::all();
```

### Checking Data

[](#checking-data)

```
// Check if key exists and is not empty
RequestBag::has(string $key): bool

// Check if key exists (even if empty)
RequestBag::exists(string $key): bool

// Example
if (RequestBag::has('user_id')) {
    // Key exists and has a value
}

if (RequestBag::exists('theme')) {
    // Key exists (might be empty)
}
```

### Removing Data

[](#removing-data)

```
// Remove a specific key
RequestBag::remove(string $key): self

// Clear all data
RequestBag::clear(): self

// Example
RequestBag::remove('temp_data');
RequestBag::clear();
```

### Method Chaining

[](#method-chaining)

All methods that modify the bag return `self` for fluent chaining:

```
RequestBag::add('key1', 'value1')
    ->add('key2', 'value2')
    ->merge(['key3' => 'value3'])
    ->remove('key1');
```

Direct Class Usage
------------------

[](#direct-class-usage)

You can also inject the class directly instead of using the facade:

```
use Bensedev\RequestBag\RequestBag;

class MyService
{
    public function __construct(
        private RequestBag $bag
    ) {}

    public function doSomething(): void
    {
        $this->bag->add('key', 'value');
    }
}
```

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Run PHPStan:

```
composer analyse
```

Run Laravel Pint:

```
composer format
```

Requirements
------------

[](#requirements)

- PHP 8.4 or higher
- Laravel 12.0 or higher

License
-------

[](#license)

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

Credits
-------

[](#credits)

- [bensedev](https://github.com/bensedev)

Support
-------

[](#support)

If you discover any issues, please open an issue on GitHub.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance67

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~0 days

Total

2

Last Release

224d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/09202caa58f25c9b9ca1b8de309e02aca5c605478fcbb5193b2ac301f0c8cc55?d=identicon)[bensedev](/maintainers/bensedev)

---

Top Contributors

[![BenSeDev](https://avatars.githubusercontent.com/u/27857775?v=4)](https://github.com/BenSeDev "BenSeDev (2 commits)")

---

Tags

requestcontainerlaravelContextbag

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/bensedev-request-bag/health.svg)

```
[![Health](https://phpackages.com/badges/bensedev-request-bag/health.svg)](https://phpackages.com/packages/bensedev-request-bag)
```

###  Alternatives

[api-platform/laravel

API Platform support for Laravel

59126.4k6](/packages/api-platform-laravel)[mlaphp/mlaphp

Library of code introduced throughout Modernizing Legacy Applications in PHP.

568.6k1](/packages/mlaphp-mlaphp)[nunomaduro/laravel-pot

Set of commands to inspect Laravel's container

991.6k](/packages/nunomaduro-laravel-pot)[daylerees/container-debug

Inspect the Laravel IoC Container from Artisan.

572.8k](/packages/daylerees-container-debug)[godruoyi/easy-container

A small PHP 5.3 dependency injection container extended from Laravel container.

334.9k2](/packages/godruoyi-easy-container)

PHPackages © 2026

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