PHPackages                             ysm/with-transaction - 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. ysm/with-transaction

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

ysm/with-transaction
====================

Laravel trait to automatically wrap model operations in transactions.

1.0.0(1y ago)10231MITPHPPHP ^8.1

Since Jun 28Pushed 1y agoCompare

[ Source](https://github.com/DevYSM/with-transaction)[ Packagist](https://packagist.org/packages/ysm/with-transaction)[ RSS](/packages/ysm-with-transaction/feed)WikiDiscussions master Synced today

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

Laravel WithTransaction Trait
=============================

[](#laravel-withtransaction-trait)

This package provides a reusable Laravel trait that automatically wraps Eloquent model operations (`create`, `update`, `save`, `delete`, etc.) in database transactions — giving you cleaner, safer code without writing `DB::transaction()` everywhere.

✨ Features
----------

[](#-features)

- Automatically wraps model actions in a transaction
- Easily toggle transaction behavior per operation
- Works with all Eloquent models
- Supports create, update, save, delete, restore, forceDelete
- Static helpers: `withTransaction`, `transaction`

---

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

[](#-installation)

```
composer require ysm/with-transaction

php artisan vendor:publish --tag=with-transaction-config
```

📖 Usage
-------

[](#-usage)

### 1. Add the Trait

[](#1-add-the-trait)

In your Eloquent model, use the `WithTransaction` trait:

```
use App\Traits\WithTransaction;

class Post extends Model
{
    use WithTransaction;

    protected $fillable = ['title', 'content'];
}
```

### 2. Use in the controller

[](#2-use-in-the-controller)

Now you can use your model as usual, and all operations will be automatically wrapped in a transaction:

```
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function store(Request $request)
    {
       $post = Post::transaction(function () use ($request) {

            $model = Post::create($request->validated());

            $model->tags()->attach(Tag::inRandomOrder()->take(3)->pluck('id'));
            $model->categories()->attach(Category::inRandomOrder()->take(3)->pluck('id'));

            $model->addMediaFromRequest('image')
                ->toMediaCollection('posts');

            // all or nothing rollback automatically
            return $model;
        });

        return response()->json([
            'message' => 'Post created successfully',
            'post' => $post,
        ]);
    }
}
```

### 3. Updating the Model

[](#3-updating-the-model)

You can also use the same trait for updating models:

```
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function Update(Request $request, Post $post)
    {
        $post = Post::transaction(function () use ($post) {

            $post->update([
                'title' => 'Update title Post v1',
            ]);

            $post->tags()->sync([4, 5, 6]);

            return $post;
       });

        return response()->json([
            'message' => 'Post updated successfully',
            'post' => $post,
        ], 200);
    }
}
```

### 4. Deleting the Model

[](#4-deleting-the-model)

You can also delete models using the same trait:

```
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
    public function destroy(Post $post)
    {
        $post = Post::transaction(function () use ($post) {
            $post->delete();
            // If you want to perform any additional operations after deletion,
            // you can do so here. For example, logging or cleaning up related data.
            // If the deletion fails, the transaction will automatically roll back.
            return $post;
        });

        return response()->json([
            'message' => 'Post deleted successfully',
            'post' => $post,
        ], 200);
    }
}
```

### Or you can use it as a helper function

[](#or-you-can-use-it-as-a-helper-function)

```
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\Request;
use YSM\Support\transaction;

class PostController extends Controller
{
    public function destroy(Post $post)
    {

        $post = transaction(function () use ($post) {
            $post->delete();
            // If you want to perform any additional operations after deletion,
            // you can do so here. For example, logging or cleaning up related data.
            // If the deletion fails, the transaction will automatically roll back.
            return $post;
        });

        return response()->json([
            'message' => 'Post deleted successfully',
            'post' => $post,
        ], 200);
    }
}
```

### 🔁 Using the Global Helper Function

[](#-using-the-global-helper-function)

Use anywhere in your app:

```
use function YSM\Support\transaction;

transaction(function () use ($post) {
    $post->update([...]);
}, attempts: 2, onSuccess: fn () => Log::info('Done!'), onFailure: fn ($e) => report($e));
```

### 🧠 Fluent Transaction Builder

[](#-fluent-transaction-builder)

Need more control? Use the fluent interface:

```
use YSM\Support\Facades\Transaction;

Transaction::start()
    ->attempts(3)
    ->onSuccess(fn ($result) => Log::info('Transaction success', ['id' => $result?->id]))
    ->onFailure(fn ($e) => Log::error('Transaction failed', ['message' => $e->getMessage()]))
    ->run(fn () => Post::create([...]));
```

### ❤️ Thank You

[](#️-thank-you)

Thanks for using this package! If it saved you time or avoided a bug, consider giving it a ⭐ on GitHub.

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance49

Moderate activity, may be stable

Popularity15

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 75% 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

Unknown

Total

1

Last Release

369d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/94ad099ac29460710c50f3c27489ebd2e8ee24d3cd5bfbaf040cd5d4a3a2dd1a?d=identicon)[Yassen Sayed](/maintainers/Yassen%20Sayed)

---

Top Contributors

[![DevYSM](https://avatars.githubusercontent.com/u/59166666?v=4)](https://github.com/DevYSM "DevYSM (12 commits)")[![yacinediaf](https://avatars.githubusercontent.com/u/110975011?v=4)](https://github.com/yacinediaf "yacinediaf (4 commits)")

---

Tags

laravelormmodeltraittransaction

### Embed Badge

![Health badge](/badges/ysm-with-transaction/health.svg)

```
[![Health](https://phpackages.com/badges/ysm-with-transaction/health.svg)](https://phpackages.com/packages/ysm-with-transaction)
```

###  Alternatives

[illuminate/database

The Illuminate Database package.

2.8k54.9M11.6k](/packages/illuminate-database)[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k8.4M96](/packages/mongodb-laravel-mongodb)[yajra/laravel-oci8

Oracle DB driver for Laravel via OCI8

8793.2M25](/packages/yajra-laravel-oci8)[cybercog/laravel-love

Make Laravel Eloquent models reactable with any type of emotions in a minutes!

1.2k332.0k1](/packages/cybercog-laravel-love)[esensi/model

The base model traits of Esensi

20167.0k1](/packages/esensi-model)[ymigval/laravel-model-cache

Laravel package for caching Eloquent model queries

7962.6k4](/packages/ymigval-laravel-model-cache)

PHPackages © 2026

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