PHPackages                             sweetmancc/mysql-trigger-for-laravel-migration - 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. sweetmancc/mysql-trigger-for-laravel-migration

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

sweetmancc/mysql-trigger-for-laravel-migration
==============================================

A package to add database trigger to laravel migrations

9642[1 issues](https://github.com/sweetmans/mysql-trigger-for-laravel-migration/issues)PHP

Since May 7Pushed 4y ago1 watchersCompare

[ Source](https://github.com/sweetmans/mysql-trigger-for-laravel-migration)[ Packagist](https://packagist.org/packages/sweetmancc/mysql-trigger-for-laravel-migration)[ RSS](/packages/sweetmancc-mysql-trigger-for-laravel-migration/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Add database trigger to laravel migrations
==========================================

[](#add-database-trigger-to-laravel-migrations)

[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Build Status](https://camo.githubusercontent.com/a6221db10e90a619603f9c319b56c4434bdec1193f8909a472a6724e5b03575f/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f4e74696d5965626f61682f6c61726176656c2d64617461626173652d747269676765722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/NtimYeboah/laravel-database-trigger)[![StyleCI](https://camo.githubusercontent.com/47ab2684185e545ba853f8c663fcb455e3fbea811437c4271ef3137099ead3c9/68747470733a2f2f6769746875622e7374796c6563692e696f2f7265706f732f373534383938362f736869656c64)](https://styleci.io/repos/7548986)

Laravel Database Trigger provides a way to add database trigger to laravel migrations just like you would with database table. A trigger is a named database object that is associated with a table, and that activates when a particular event occurs for the table. Read more about triggers [here](https://dev.mysql.com/doc/refman/8.0/en/triggers.html).

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

[](#installation)

Laravel Database Trigger requires at least [PHP](https://php.net) 7.2. This particular version supports laravel at least v6.0 The package currently supports MySQL only.

To get the latest version, simply require the package using [Composer](https://getcomposer.org):

```
$ composer require sweetmancc/mysql-trigger-for-laravel-migration
```

Once installed, if you are not using automatic package discovery, then you need to register the `Sweetmancc\DatabaseTrigger\TriggerServiceProvider` service provider in your `config/app.php`.

Usage
-----

[](#usage)

Create a trigger migration file using the `make:trigger` artisan command. The command requires the name of the trigger, name of the event object table, action timing and the event that activates the trigger.

```
$ php artisan make:trigger after_users_posts_insert
```

### Event object table

[](#event-object-table)

The event object table is the name of the table the trigger is associated with.

### Action timing

[](#action-timing)

The activation time for the trigger. Possible values are `after` and `before`.

`after` - Process action after the change is made on the event object table.

`before` - Process action prior to the change is made on the event object table.

### Event

[](#event)

The event to activate trigger. A trigger event can be `insert`, `update` and `delete`.

`insert` - Activate trigger when an insert operation is performed on the event object table.

`update` - Activate trigger when an update operation is performed on the event object table.

`delete` - Activate trigger when a delete operation is performed on the event object table.

The following trigger migration file will be generated for a trigger that uses `after_users_posts_insert` as a name, `user_posts` as event object table name, `after` as action timing and `insert` as event.

```
use Illuminate\Database\Migrations\Migration;
use Sweetmancc\DatabaseTrigger\TriggerFacade as Schema;

class CreateAfterUsersUpdateTrigger extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('after_users_posts_insert')
            ->on('user_posts')
            ->statement(function() {
                return '//You logic, Don't forget ";" ';
            })
            ->after()
            ->update();
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users.after_users_posts_insert');
    }
}
```

Return the trigger statement from the closure of the `statement` method.

The following is an example trigger migration to insert into the `users_audit` table after updating a user row.

```
...

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('after_user_posts_insert')
            ->on('user_posts')
            ->statement(function() {
                //It means that when insert an row into user_posts table It will inrease 1 to user_profiles table where row record user_id same as NEW insert to user_posts table user_id field.
                return 'UPDATE user_profiles SET postCount = postCount + 1 WHERE id = NEW.user_id;';
            })
            ->after()
            ->update();
    }

...
```

### Update your database migration

[](#update-your-database-migration)

```
php artisan migrate
```

### My mysql Database Tables `user_posts` &amp; `user_profiles`

[](#my-mysql-database-tables-user_posts--user_profiles)

```
CREATE TABLE `user_posts` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `user_id` bigint(20) unsigned NOT NULL,
  `text` text COLLATE utf8mb4_unicode_ci,
  PRIMARY KEY (`id`),
  KEY `user_posts_user_id_foreign` (`user_id`),
  CONSTRAINT `user_posts_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `user_profiles` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` bigint(20) unsigned NOT NULL,
  `postCount` int(11) NOT NULL DEFAULT '0',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `user_profiles_user_id_unique` (`user_id`),
  CONSTRAINT `user_profiles_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

Testing
-------

[](#testing)

Run the tests with:

```
$ composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](https://github.com/sweetmans/mysql-trigger-for-laravel-migration/blob/master/CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/sweetmans/mysql-trigger-for-laravel-migration/blob/master/CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover a security vulnerability within this package, please send an e-mail to Andy Q at . All security vulnerabilities will be promptly addressed.

License
-------

[](#license)

Laravel Database Trigger is licensed under [The MIT License (MIT)](LICENSE).

###  Health Score

20

—

LowBetter than 14% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity16

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity30

Early-stage or recently created project

 Bus Factor1

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

### Community

Maintainers

![](https://www.gravatar.com/avatar/dccfcd96f5a6e34090d1b56be3afc8be6f0693fff24dc7f34cddb7b163d6c527?d=identicon)[sweetmancc](/maintainers/sweetmancc)

---

Top Contributors

[![sweetmans](https://avatars.githubusercontent.com/u/22865790?v=4)](https://github.com/sweetmans "sweetmans (6 commits)")[![boryn](https://avatars.githubusercontent.com/u/807297?v=4)](https://github.com/boryn "boryn (1 commits)")

### Embed Badge

![Health badge](/badges/sweetmancc-mysql-trigger-for-laravel-migration/health.svg)

```
[![Health](https://phpackages.com/badges/sweetmancc-mysql-trigger-for-laravel-migration/health.svg)](https://phpackages.com/packages/sweetmancc-mysql-trigger-for-laravel-migration)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M546](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

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