This package provides an easy way to manage database triggers within your Laravel application. Currently only MySQL is supported.
You can install the package via composer:
composer require esign/laravel-database-trigger
To create a new database trigger, use the createTrigger
method on the Schema
facade.
The createTrigger
method accepts two arguments: the first is the name of the trigger, while the second is a closure which receives a DatabaseTrigger
object that may be used to define the new trigger:
use Esign\DatabaseTrigger\DatabaseTrigger;
use Esign\DatabaseTrigger\Enums\TriggerEvent;
use Esign\DatabaseTrigger\Enums\TriggerTiming;
use Esign\DatabaseTrigger\Facades\Schema;
Schema::createTrigger('my_trigger', function (DatabaseTrigger $trigger) {
$trigger->on('posts');
$trigger->event(TriggerEvent::INSERT);
$trigger->timing(TriggerTiming::BEFORE);
$trigger->statement("SET NEW.title = 'Default title';");
});
You may check for the existence of a trigger by using the hasTrigger
method:
use Esign\DatabaseTrigger\Facades\Schema;
Schema::hasTrigger('my_trigger');
You may drop an existing trigger by using the dropTrigger
or dropTriggerIfExists
methods:
use Esign\DatabaseTrigger\Facades\Schema;
Schema::dropTrigger('my_trigger');
Schema::dropTriggerIfExists('my_trigger');
You may use the make:trigger
artisan command to quickly generate a trigger migration:
php artisan make:trigger
This will publish a migration with the following contents:
use Esign\DatabaseTrigger\DatabaseTrigger;
use Esign\DatabaseTrigger\Enums\TriggerEvent;
use Esign\DatabaseTrigger\Enums\TriggerTiming;
use Esign\DatabaseTrigger\Facades\Schema;
use Illuminate\Database\Migrations\Migration;
return new class extends Migration
{
public function up(): void
{
Schema::createTrigger('before_posts_update', function (DatabaseTrigger $trigger) {
$trigger->on('posts');
$trigger->timing(TriggerTiming::BEFORE);
$trigger->event(TriggerEvent::UPDATE);
$trigger->statement('');
});
}
public function down(): void
{
Schema::dropTriggerIfExists('before_posts_update');
}
};
A name for the trigger will automatically be created based on the provided input. In case you want to use a diffferent trigger name, you may pass it as the first argument:
php artisan make:trigger my_trigger
To display a list of your existing triggers you may use the trigger:list
command:
php artisan trigger:list
php artisan trigger:list <connection>
composer test
The MIT License (MIT). Please see License File for more information.