How to Add MySQL Trigger from Migration in Laravel?
Sometimes you require to add trigger in your mysql database of laravel. but you think how to create trigger using laravel migration because laravel not provide special function like insertTrigger and something so it problem to create direclty, But laravel DB::unprepared() through we can create trigger for database.
In Following example you can see how to create migration and create trigger code and how to write drop trigger code, so let's do it this way.
Run the following command to create migration:
php artisan make:migration add_trigger
class AddTrigger extends Migration
public function up()
DB::unprepared('CREATE TRIGGER add_Item_city AFTER INSERT ON `items` FOR EACH ROW
INSERT INTO `items_city` (`item_id`) VALUES (NEW.id);
public function down()
DB::unprepared('DROP TRIGGER `add_Item_city`');
php artisan migrate
We are Recommending you
- How to Create Migration in Laravel 9?
- How to Run Migration and Seeder on Laravel Vapor?
- How to Change Column Length using Laravel Migration?
- How to Update Enum Value in Laravel Migration?
- Laravel Migration Enum Default Value Example
- Laravel Migration Add Enum Column Example
- Laravel Migration Add Comment to Column Example
- Laravel Migration Custom Index Name Example
- How to Add Foreign Key in Laravel Migration?
- How to Change Table Name using Laravel Migration?
- How to Remove Column from Table in Laravel Migration?
- How to Change Column Name and Data Type in Laravel Migration?
- How to Create Table using Migration in Laravel?