PHPackages                             m-sonmez/laravel-triggers - 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. m-sonmez/laravel-triggers

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

m-sonmez/laravel-triggers
=========================

Database-agnostic fluent trigger builder for Laravel Migrations.

1.0.1(3mo ago)05MITPHPPHP ^8.2CI passing

Since Apr 11Pushed 3mo agoCompare

[ Source](https://github.com/m-sonmez/laravel-triggers)[ Packagist](https://packagist.org/packages/m-sonmez/laravel-triggers)[ Docs](https://github.com/m-sonmez/laravel-triggers)[ RSS](/packages/m-sonmez-laravel-triggers/feed)WikiDiscussions main Synced 3w ago

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

Laravel Triggers
================

[](#laravel-triggers)

[![Latest Version on Packagist](https://camo.githubusercontent.com/09153b73a8b86c87f1e13872fd3c2b444f304f58b643a21a42c83460d431a783/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d2d736f6e6d657a2f6c61726176656c2d74726967676572732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/m-sonmez/laravel-triggers)[![GitHub Tests Action Status](https://camo.githubusercontent.com/004fe768788461a34b8a8daed9203f0ad9e18302c77d7b4c25089f080fe694de/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d2d736f6e6d657a2f6c61726176656c2d74726967676572732f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/m-sonmez/laravel-triggers/actions)[![Total Downloads](https://camo.githubusercontent.com/10a9223a12c37eea1b032f43b5445c53d8e0de4ae6bc497ed9ec22e18fcff8e5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d2d736f6e6d657a2f6c61726176656c2d74726967676572732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/m-sonmez/laravel-triggers)

A database-agnostic fluent trigger builder for Laravel Migrations. Write your trigger logic once in PHP and deploy to **SQLite, MySQL, MariaDB, PostgreSQL, or SQL Server (MSSQL)**.

Why use this?
-------------

[](#why-use-this)

Laravel's Schema builder doesn't natively support triggers. Usually, you have to write raw SQL strings that vary wildly between database engines. This package allows you to use a fluent API to define triggers that work everywhere.

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

[](#requirements)

- **PHP**: ^8.2
- **Laravel**: ^12.0 or ^13.0

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

[](#installation)

You can install the package via composer:

```
composer require m-sonmez/laravel-triggers
```

Usage
-----

[](#usage)

### Simple Log Trigger

[](#simple-log-trigger)

The most common use case is logging changes to an actions or logs table.

```
use Msonmez\LaravelTriggers\Enums\TriggerTiming;
use Msonmez\LaravelTriggers\Enums\TriggerEvent;
use Msonmez\LaravelTriggers\Helpers\Trigger;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::table('accounts', function (Blueprint $table) {
    $table->trigger(
        name: 'LogAccountCreation',
        timing: TriggerTiming::AFTER,
        event: TriggerEvent::INSERT,
        statements: Trigger::insert('actions', [
            'type' => 1,
            'table_name' => 'accounts',
            'record_id' => Trigger::new('id'),
            'created_at' => Trigger::now(),
        ])
    );
});
```

### Complex Conditional Logic

[](#complex-conditional-logic)

Prevent specific actions by throwing database-level exceptions based on conditions.

```
$table->trigger(
    name: 'PreventSelfConnection',
    timing: TriggerTiming::BEFORE,
    event: TriggerEvent::INSERT,
    condition: 'NEW.sender_id = NEW.receiver_id',
    statements: Trigger::abort('Users cannot connect to themselves')
);
```

### Incrementing Counters

[](#incrementing-counters)

Keep your counters in sync automatically.

```
$table->trigger(
    name: 'IncrementPostCount',
    timing: TriggerTiming::AFTER,
    event: TriggerEvent::INSERT,
    statements: Trigger::increment('users', 'posts_count', 1, 'id = ' . Trigger::new('user_id'))
);
```

### Dropping Triggers

[](#dropping-triggers)

You can easily drop triggers in your `down()` method.

```
Schema::table('accounts', function (Blueprint $table) {
    $table->dropTrigger('LogAccountCreation');
});
```

### Checking if a Trigger exists

[](#checking-if-a-trigger-exists)

You can easily check if a trigger exists.

```
Schema::table('accounts', function (Blueprint $table) {
    if ($table->hasTrigger('LogAccountCreation')) {
        // do operations based on the existence of a trigger
    }
});
```

### Advanced Examples

[](#advanced-examples)

#### Cross-Table Validation

[](#cross-table-validation)

Prevent an action based on a value in another table.

```
$table->trigger(
    name: 'CheckUserBalance',
    timing: TriggerTiming::BEFORE,
    event: TriggerEvent::INSERT,
    condition: '(SELECT balance FROM users WHERE id = NEW.user_id) < NEW.amount',
    statements: Trigger::abort('Insufficient balance for this transaction')
);
```

#### Complex Multi-Statement Logic

[](#complex-multi-statement-logic)

Perform multiple actions in a single trigger.

```
$table->trigger(
    name: 'ProcessOrder',
    timing: TriggerTiming::AFTER,
    event: TriggerEvent::INSERT,
    statements: [
        Trigger::update('inventory', ['stock' => Trigger::expr('stock - ' . Trigger::new('quantity'))], 'product_id = ' . Trigger::new('product_id')),
        Trigger::insertSelect('order_logs', ['order_id', 'status'], 'SELECT id, "processed" FROM orders WHERE id = ' . Trigger::new('id'))
    ]
);
```

#### Soft-Delete Handling

[](#soft-delete-handling)

Automatically clean up related records when a record is "soft-deleted" (if using a custom flag).

```
$table->trigger(
    name: 'CleanupOnSoftDelete',
    timing: TriggerTiming::AFTER,
    event: TriggerEvent::UPDATE,
    condition: 'OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL',
    statements: Trigger::update('related_items', ['active' => 0], 'parent_id = ' . Trigger::new('id'))
);
```

Supported Database Tokens
-------------------------

[](#supported-database-tokens)

The package handles the dialect differences for common operations:

- `Trigger::now()`: Current timestamp.
- `Trigger::date()`: Current date.
- `Trigger::uuid()`: Generates a HEX UUID.
- `Trigger::new('column')`: References the `NEW` row state.
- `Trigger::old('column')`: References the `OLD` row state.
- `Trigger::expr('sql')`: Wraps raw SQL to prevent quoting.
- `Trigger::call('func', ['arg1', Trigger::new('col')])`: Calls a database function with quoted arguments.

Supported Databases
-------------------

[](#supported-databases)

- **SQLite** (uses `WHEN` and `strftime`)
- **MySQL / MariaDB** (uses `FOR EACH ROW`, `IF/THEN`, and `DATE_FORMAT`)
- **PostgreSQL** (automatically creates/manages the required `plpgsql` functions)
- **SQL Server (MSSQL)** (uses `INSTEAD OF` for BEFORE, and `inserted`/`deleted` tables)

IDE Support
-----------

[](#ide-support)

This package includes an IDE helper to provide method completion for the `Blueprint` class. Most IDEs will pick this up automatically. If your IDE doesn't recognize the `trigger`, `hasTrigger`, or `dropTrigger` methods, you can add a type hint in your migration:

```
use Illuminate\Database\Schema\Blueprint;

Schema::table('users', function (Blueprint $table) {
    /** @var Blueprint $table */
    $table->trigger(...);
});
```

Testing
-------

[](#testing)

```
composer test
```

Local Development
-----------------

[](#local-development)

To set up the project for local development:

```
composer setup
```

This will install all PHP dependencies and set up your environment.

License
-------

[](#license)

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

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance81

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

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

Total

2

Last Release

103d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/11619503?v=4)[Murat Sönmez](/maintainers/m-sonmez)[@m-sonmez](https://github.com/m-sonmez)

---

Top Contributors

[![m-sonmez](https://avatars.githubusercontent.com/u/11619503?v=4)](https://github.com/m-sonmez "m-sonmez (2 commits)")

---

Tags

laraveldatabasemysqlsqlitepostgresqlsqlservermssqlmigrationsfluenttrigger

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/m-sonmez-laravel-triggers/health.svg)

```
[![Health](https://phpackages.com/badges/m-sonmez-laravel-triggers/health.svg)](https://phpackages.com/packages/m-sonmez-laravel-triggers)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.3M347](/packages/psalm-plugin-laravel)[ramadan/custom-fresh

A Laravel package to specify the tables that you do not want to drop while refreshing the database.

611.6k](/packages/ramadan-custom-fresh)[ramadan/easy-model

A Laravel package for enjoyably managing database queries.

111.6k](/packages/ramadan-easy-model)[moharrum/laravel-adminer

Adminer database management tool for your Laravel application.

451.0k](/packages/moharrum-laravel-adminer)

PHPackages © 2026

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