PHPackages                             fuyuan9/livewire-optimistic-actions - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. fuyuan9/livewire-optimistic-actions

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

fuyuan9/livewire-optimistic-actions
===================================

Declarative optimistic actions for Livewire. Server-first, Blade-first, rebase-first.

1.0.1(1mo ago)00MITTypeScriptPHP ^8.2CI passing

Since Jun 6Pushed 1mo agoCompare

[ Source](https://github.com/fuyuan9/livewire-optimistic-actions)[ Packagist](https://packagist.org/packages/fuyuan9/livewire-optimistic-actions)[ RSS](/packages/fuyuan9-livewire-optimistic-actions/feed)WikiDiscussions main Synced 1w ago

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

Livewire Optimistic Actions
===========================

[](#livewire-optimistic-actions)

[![Latest Version on Packagist](https://camo.githubusercontent.com/fe54b8b04f2dcda3581b21b69f7017bc517aed7284801621a1278e35a71a0e94/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f66757975616e392f6c697665776972652d6f7074696d69737469632d616374696f6e732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/fuyuan9/livewire-optimistic-actions)[![Total Downloads](https://camo.githubusercontent.com/c2457e5b933ff6931456c31165ebbc3a7e751d62a0158f3e881a54216f025c45/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f66757975616e392f6c697665776972652d6f7074696d69737469632d616374696f6e732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/fuyuan9/livewire-optimistic-actions)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)

> **Declarative optimistic actions for Livewire.**
> *Server-first, Blade-first, rebase-first.*

`livewire-optimistic-actions` is an ultra-lightweight and robust extension package that adds declarative optimistic UI updates to Laravel Livewire v3 actions.

---

💡 Package Concept
-----------------

[](#-package-concept)

This package is **not** a client-side state management library. Nor does it attempt to force Livewire to work like React.

- **The server is always the single source of truth.**
- Optimistic changes act as a **temporary client-side overlay** until the server response is received.
- On a successful response, the new state from the server is finalized. On failure, it automatically performs a **rebase rollback** to the original state.
- It uses a **Rebase Model** that maintains order and reapplies pending updates even when actions are spammed or multiple requests occur concurrently.

---

✨ Features (v1.0.1)
-------------------

[](#-features-v101)

- **Simple Blade Attribute API**: Works simply by adding HTML attributes (`optimistic:*`).
- **Rich Scalar Updates**: Supports `increment`, `decrement`, and `set`.
- **Collection Operations**: Supports `remove` (instantly hiding items from a list).
- **Pending and Failed UI States**: Indicators using `optimistic:pending` and `optimistic:failed`.
- **Robust Rebase Model**: Instead of a simple "rollback to previous value" mechanism, it overlays unresolved optimistic updates on top of the latest server state, making it highly resilient to concurrent requests.

---

📦 Installation
--------------

[](#-installation)

```
composer require fuyuan9/livewire-optimistic-actions
```

To load the assets, add the Blade directive immediately after `@livewireScripts` in your layout file (e.g., `app.blade.php`).

```
    @livewireScripts
    @livewireOptimisticActions

```

---

🎯 Common Use Cases
------------------

[](#-common-use-cases)

This package is extremely effective in scenarios where you want to hide network latency from users while ensuring automatic rollbacks in case of operation errors or communication failures.

### 1. Like, Bookmark, and Favorite Buttons on Social Media

[](#1-like-bookmark-and-favorite-buttons-on-social-media)

- **Challenge**: When a user clicks a like button, if there is a delay in the count or icon update before the server responds, they might feel the app is unresponsive and click the button repeatedly.
- **Solution**: The moment the button is clicked, `optimistic:increment` increases the count by "+1" and activates the button visual. The request is sent in the background, and if a network or server error occurs, it automatically decrements by "-1" back to its original state.

### 2. Deleting Items from Lists or Tables (To-Do Lists, Shopping Carts, etc.)

[](#2-deleting-items-from-lists-or-tables-to-do-lists-shopping-carts-etc)

- **Challenge**: When deleting a product or task, waiting for the server-side database deletion to complete before updating the UI creates a sluggish user experience.
- **Solution**: By setting `optimistic:remove`, the targeted item or row vanishes instantly from the screen. If the server-side deletion fails (e.g., lack of permission, database error), the item is automatically restored to its original place (rollback).

### 3. Immediate Status Toggle (Publish/Draft, Enable/Disable)

[](#3-immediate-status-toggle-publishdraft-enabledisable)

- **Challenge**: When toggling an article from "Draft" to "Published", if server-side processing (CDN purging, external APIs) takes a few seconds, the delayed toggle response can confuse users.
- **Solution**: Use `optimistic:set` to instantly change the badge or toggle state to "Published". The user can proceed with other tasks without waiting.

---

⚖️ Benefits of Using the Package vs. Manual Implementation
----------------------------------------------------------

[](#️-benefits-of-using-the-package-vs-manual-implementation)

Optimistic UI updates can be implemented without this package by combining Alpine.js and Livewire. However, doing so manually introduces significant boilerplate and concurrency issues.

### Example of Manual Implementation (Without Package)

[](#example-of-manual-implementation-without-package)

Here is how you would manually implement an optimistic update and rollback for a "Like" button:

```

        👍 Like

    Saving...
    Failed to save.

```

#### Challenges of Manual Implementation:

[](#challenges-of-manual-implementation)

1. **Massive Boilerplate**: For every single feature (like, delete, toggle, etc.), you must manually define Alpine components to manage temporary variables (`prevLikes`), loading states, and error states.
2. **Broken Concurrency (Race Conditions)**: If a user clicks a button twice quickly, or if other asynchronous actions run concurrently, `prevLikes` will get overwritten with the intermediate state (`11`). Consequently, when a rollback happens, the UI reverts to an incorrect state instead of the original state (`10`).
3. **Complex List Operations**: Writing array manipulation code to "instantly hide an element and restore it on error" for a collection like a To-Do list is even more complicated.

---

### 🎁 Benefits of Using This Package

[](#-benefits-of-using-this-package)

1. **HTML-Only Zero Boilerplate**: No need for Alpine.js `x-data` or complex JS logic. You can implement it simply by adding attributes like `optimistic:increment` or `optimistic:remove` to your existing HTML/Blade templates.
2. **Robust Concurrency (Rebase Model)**: Instead of just saving and restoring the last value, it uses a Git-like rebase model: **"reapply pending optimistic actions on top of the latest canonical state confirmed by the server."** This keeps the UI perfectly in sync even during button spamming or parallel actions.
3. **Declarative Loading &amp; Error Controls**: Just specify `optimistic:pending="actionName"` and `optimistic:failed="actionName"` to automatically handle loading indicators and error states during async actions.

---

🚀 Usage
-------

[](#-usage)

### 1. Counter Increment / Decrement (Likes, etc.)

[](#1-counter-increment--decrement-likes-etc)

```

    👍 Like

{{ $likes }}

Saving...
Failed to save.
```

### 2. Set Status (Assignment)

[](#2-set-status-assignment)

```

    🚀 Publish

{{ $status }}
```

### 3. Remove Item from Collection

[](#3-remove-item-from-collection)

Instantly hides elements with a specified key/value from arrays or collections.

```
@foreach($todos as $todo)

        {{ $todo['title'] }}

            Delete

@endforeach
```

---

🛠️ Docker Local Development Environment
---------------------------------------

[](#️-docker-local-development-environment)

This package includes a complete Docker environment for developing and testing PHP and JavaScript without polluting your host machine.

### Prerequisites

[](#prerequisites)

- Docker &amp; Docker Compose
- Make (Optional but recommended)

### Development Steps

[](#development-steps)

1. Clone the repository.
2. Build and start `docker compose`. ```
    make build
    make up
    ```
3. Set up the environment file. ```
    cp .env.example .env
    ```

    And generate an application key: ```
    docker compose exec app ./vendor/bin/testbench key:generate
    ```
4. Install dependencies. ```
    make composer-install
    make npm-install
    ```
5. Build frontend assets. ```
    make build-js
    ```
6. Run tests. ```
    make test      # Run both PHPUnit and Vitest
    make test-php  # Run PHPUnit tests only
    make test-js   # Run Vitest (TypeScript) tests only
    ```
7. Start the demo server. ```
    make demo
    ```

    Access `http://localhost:8000` in your browser to see the interactive demo (demonstrating the likes counter, status toggles, deletion rollback behavior, etc.).

---

🧪 Testing
---------

[](#-testing)

### JavaScript / TypeScript Runtime Tests (Vitest)

[](#javascript--typescript-runtime-tests-vitest)

Tests client-side patching, dot-path resolution, and the Rebase model queue logic.

```
make test-js
```

### PHP Integration Tests (PHPUnit)

[](#php-integration-tests-phpunit)

Tests Laravel service provider registration and Blade asset injection directive registration.

```
make test-php
```

---

⚠️ Limitations (v1.0.1)
-----------------------

[](#️-limitations-v101)

- **Offline Mode**: Not supported. Active server communication is required.
- **Deeply Nested Collections**: Supports only simple ID removal from collections. Deep nested reconciliation is not performed.
- **Temporary ID Replacement**: Not supported.

---

📄 License
---------

[](#-license)

Released under the MIT License. See [LICENSE.md](LICENSE.md) for details.

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance90

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

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

48d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/45146854?v=4)[fuyuan9](/maintainers/fuyuan9)[@fuyuan9](https://github.com/fuyuan9)

---

Top Contributors

[![fuyuan9](https://avatars.githubusercontent.com/u/45146854?v=4)](https://github.com/fuyuan9 "fuyuan9 (8 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/fuyuan9-livewire-optimistic-actions/health.svg)

```
[![Health](https://phpackages.com/badges/fuyuan9-livewire-optimistic-actions/health.svg)](https://phpackages.com/packages/fuyuan9-livewire-optimistic-actions)
```

###  Alternatives

[tallstackui/tallstackui

TallStackUI is a powerful suite of Blade components that elevate your workflow of Livewire applications.

728176.2k14](/packages/tallstackui-tallstackui)[psalm/plugin-laravel

Psalm plugin for Laravel

3345.3M347](/packages/psalm-plugin-laravel)[illuminate/pipeline

The Illuminate Pipeline package.

9349.2M291](/packages/illuminate-pipeline)[illuminate/pagination

The Illuminate Pagination package.

10534.1M1.1k](/packages/illuminate-pagination)[illuminate/redis

The Illuminate Redis package.

8314.6M388](/packages/illuminate-redis)[spatie/laravel-export

Create a static site bundle from a Laravel app

674146.0k6](/packages/spatie-laravel-export)

PHPackages © 2026

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