This package enables the use of database triggers within Laravel applications. Note that your chosen database must support triggers for the package to work.
Pull in the package using Composer:
composer require caneara/triggers
Triggers can only be added to existing tables. Therefore, when creating triggers in your migration files, make sure you add them after the Schema::create
method.
To create a trigger, simply call the table
method on the Triggers\Trigger
class:
use Triggers\Trigger;
Trigger::table('posts');
By default, the class will generate a name for the trigger using the following convention:
trigger_{TABLE}_{TIME}_{EVENT}
However, since trigger names must be unique across the database, if you were to create two triggers that used the same event and time (these concepts are covered in the next section), then you'd get an error.
To address this problem, the class offers a key
method that allows you to add your own custom text to the trigger's name, thereby ensuring that the trigger name can be made unique:
Trigger::table('posts')->key('custom');
When a key is specified, the trigger name is derived from the following convention:
trigger_{TABLE}_{KEY}_{TIME}_{EVENT}
Next, you need to specify whether the trigger should be fired for an INSERT
, UPDATE
or DELETE
event. You will also need to specify whether the trigger should run BEFORE
or AFTER
the event has taken place:
Trigger::table('posts')->beforeDelete();
Trigger::table('posts')->beforeInsert();
Trigger::table('posts')->beforeUpdate();
Trigger::table('posts')->afterDelete();
Trigger::table('posts')->afterInsert();
Trigger::table('posts')->afterUpdate();
The final step, is to specify the SQL statement(s) that should be executed by the trigger when it is fired. To do this, supply a Closure
to the event / time method. Note that the Closure
must return a SQL string
e.g.
Trigger::table('posts')->afterInsert(function() {
return "UPDATE `users` SET `posts` = 1 WHERE `id` = NEW.user_id;";
});
The following example shows a migration that creates a posts
table and then assigns the trigger to it.
use Triggers\Trigger;
class CreatePostsTable extends Migration
{
public function up() : void
{
Schema::create('posts', function(Blueprint $table) {
$table->unsignedTinyInteger('id');
$table->string('title');
});
Trigger::table('posts')->key('count')->afterInsert(function() {
return "UPDATE `users` SET `posts` = 1 WHERE `id` = NEW.user_id;";
});
}
}
Thank you for considering a contribution to the project. You are welcome to submit a PR containing improvements, however if they are substantial in nature, please also be sure to include a test or tests.
The MIT License (MIT). Please see License File for more information.