PHPackages                             mkd/laravel-state-management - 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. [Caching](/categories/caching)
4. /
5. mkd/laravel-state-management

ActiveLibrary[Caching](/categories/caching)

mkd/laravel-state-management
============================

a state management package for Laravel, enabling shared and persistent application state across services, requests, and files without the need for reinitialization. It supports casting, default state handling, and custom methods for managing complex state in your Laravel applications

v0.0.2(1y ago)57MITPHPPHP ^8.0

Since Oct 17Pushed 1y ago1 watchersCompare

[ Source](https://github.com/mustafakhaleddev/laravel-state-management)[ Packagist](https://packagist.org/packages/mkd/laravel-state-management)[ Docs](https://github.com/mustafakhaleddev/laravel-state-management)[ RSS](/packages/mkd-laravel-state-management/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (2)Versions (3)Used By (0)

Laravel State Management
========================

[](#laravel-state-management)

A state management solution for Laravel applications inspired by Redux, designed to manage complex application state across services, caching layers, and requests, with support for casting, default state handling, and custom methods.

Features
--------

[](#features)

- **Shared State Across Application**:Stores are shared globally across the application, making them easily accessible without reinitialization in multiple files.
- **State Persistence and Rehydration**: Manage application state easily, persisting and rehydrating data as needed.
- **Casting Attributes**: Automatically cast attributes to types like collections or custom classes using Laravel's castable functionality.
- **Default State Handling**: Define fallback states to be used when rehydration fails.
- **Custom Store Logic**: Add custom methods to interact with specific store states and manage application logic.

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

[](#installation)

Install the package using Composer:

```
composer require mkd/laravel-state-management
```

Basic Usage
-----------

[](#basic-usage)

### Step 1: Create a Store

[](#step-1-create-a-store)

You can create a store class using the `store:make` Artisan command:

```
php artisan store:make UserStore
```

This command will generate a new store class in your `app/Stores` directory.

### Step 2: Define Your Store

[](#step-2-define-your-store)

In the generated store, define your attributes and casts. The store will manage the state related to these attributes:

```
class UserStore extends StoreContract
{
    protected $attributes = [
        'user',
        'email',
        'status'
    ];

    protected $casts = [
        'email' => StringCast::class,  // Custom cast
    ];

    protected $enums = [
        'status' => CustomStatusEnum::class // Use enums for statuses
    ];

    public function default(): array
    {
        return ['user' => User::find($this->key)]; // Fallback if rehydration fails
    }

    public function updateUserName($name)
    {
        $user = $this->getUser();
        $user->name = $name;
        $user->save();
    }
}
```

### Step 3: Using a Store

[](#step-3-using-a-store)

To interact with a store and manage the state, you can retrieve the store instance and access its methods:

```
use App\Stores\UserStore;

public function handleState(StateManagement $stateManagement)
{
    // Retrieve the store and set state values
    $userStore = $stateManagement->store(UserStore::class);
    $userStore->setUser(User::first());

    // Call custom methods to manage store data
    $userStore->updateUserName('New Name');
}
```

### Step 4: Handling Persistent State

[](#step-4-handling-persistent-state)

You can persist and rehydrate states based on a unique key, enabling state restoration between requests:

```
$userStore = StateManagement::use(UserStore::class);
$userStore->setKey(1);
$userStore->rehydrate();
$status = $userStore->getStatus(); // Retrieve status from the store
```

### Step 5: Defining Custom Casts

[](#step-5-defining-custom-casts)

If you need custom casting for certain attributes, use the `store-cast:make` command:

```
php artisan store-cast:make EmailCast
```

Then, define the casting logic in the generated cast class:

```
class EmailCast implements StateCastAttribute
{
    public function get($model, string $key, $value, array $attributes)
    {
        return strtolower($value);
    }

    public function set($model, string $key, $value, array $attributes)
    {
        return strtoupper($value);
    }
}
```

### Store Rehydration Example

[](#store-rehydration-example)

```
$settingsStore = StateManagement::use(SettingsStore::class);
$settingsStore->setKey(auth()->user()->id);
$settingsStore->rehydrate();
$countries = $settingsStore->getCountries();
```

Commands
--------

[](#commands)

- `store:make `: Generates a new store class.
- `store-cast:make `: Generates a new custom cast class.

Example Stores
--------------

[](#example-stores)

### `SettingsStore`

[](#settingsstore)

This store manages application settings and allows for the dynamic update of user preferences.

```
class SettingsStore extends StoreContract
{
    protected $attributes = ['countries', 'cities', 'user'];

    protected $casts = ['countries' => CollectionCast::class, 'cities' => CollectionCast::class];

    public function default(): array
    {
        return ['countries' => ['id' => 1, 'name' => 'USA'], 'cities' => ['id' => 2, 'name' => 'New York']];
    }

    public function updateUserSettings($key, $value)
    {
        $this->getUser()->updateSettings($key, $value);
    }
}
```

### `UserNotification`

[](#usernotification)

This store handles sending notifications, such as emails, to users.

```
class UserNotification extends StoreContract
{
    protected $attributes = ['user', 'email'];

    protected $casts = ['email' => EmailCast::class];

    public function sendInvoiceEmail(Invoice $invoice)
    {
        $this->getUser()->notify(new InvoiceEmail($invoice));
    }
}
```

### `Persist`

[](#persist)

By Default Persist is saving the state object in cache so it can be easy rehydrated later with the key

```
use App\Stores\UserStore;

public function handleState(StateManagement $stateManagement)
{
    $user = User::first();
    // Retrieve the store and set state values
    $userStore = $stateManagement->store(UserStore::class);
    $userStore->setUser($user);
    $userStore->setKey($user->id);

    // Call custom methods to manage store data
    $userStore->updateUserName('New Name');
    $userStore->persist();
}
```

You can override `persist` logic by implementing your own logic in store class

```
    public function persistUsing()
    {
        //Your own persist logic

        //Init custom persist flag
        $this->initCustomPersist()
    }
```

### `rehydrate`

[](#rehydrate)

By Default rehydrate is setting the state from cache based on store key

```
use App\Stores\UserStore;

public function handleState(StateManagement $stateManagement)
{
    $user = User::first();
    // Retrieve the store and set state values
    $userStore = $stateManagement->store(UserStore::class);
    $userStore->setKey($user->id);
    $userStore->rehydrate();
    $userStore->getUser()->name // 'New Name'
}
```

You can override `rehydrate` logic by implementing your own logic in store class

```
    public function rehydrateUsing()
    {
        // your own rehydrating logic

        //Init custom rehydrate flag
        $this->initCustomRehydrate();
    }
```

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE.md).

---

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance37

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity35

Early-stage or recently created project

 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 ~1 days

Total

2

Last Release

571d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/25182746?v=4)[Mustafa Khaled](/maintainers/mustafakhaleddev)[@mustafakhaleddev](https://github.com/mustafakhaleddev)

---

Top Contributors

[![mustafakhaleddev](https://avatars.githubusercontent.com/u/25182746?v=4)](https://github.com/mustafakhaleddev "mustafakhaleddev (3 commits)")

---

Tags

laravellaravel-frameworklaravel-packagestate-machinestate-managementstateslaravellaravel-packagecachingglobal statestate managementreduxShared StatePersistent StateStore CastingState RehydrationCustom Store MethodsState AttributesLaravel CastsState Persistencelaravel-state-management

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mkd-laravel-state-management/health.svg)

```
[![Health](https://phpackages.com/badges/mkd-laravel-state-management/health.svg)](https://phpackages.com/packages/mkd-laravel-state-management)
```

###  Alternatives

[maartenstaa/laravel-41-route-caching

This package allows you to cache your routes definitions, thereby speeding up each request.

25371.9k](/packages/maartenstaa-laravel-41-route-caching)[swiggles/memcache

Memcache driver for Laravel 5

1449.9k1](/packages/swiggles-memcache)[byerikas/cache-tags

Allows for Redis/Valkey cache flushing multiple tagged items by a single tag.

1413.9k](/packages/byerikas-cache-tags)[matthewbdaly/laravel-repositories

A base repository class and interface, together with a caching decorator. Extend them for use in your own projects.

121.2k3](/packages/matthewbdaly-laravel-repositories)

PHPackages © 2026

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