Sometimes you need to add trigger in your mysql database of laravel 5.But how to create a trigger using laravel so 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.
So here i'm going to to show you how to create migration and create trigger code and how to write drop trigger code, so let's do it this way.
php artisan make:migration create_trigger
Create a Controller for trigger function :
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTrigger extends Migration { public function up() { DB::unprepared('CREATE TRIGGER add_employees_salary AFTER INSERT ON `employees` FOR EACH ROW BEGIN INSERT INTO `employees_salary` (`employee_id`) VALUES (NEW.id); END'); } public function down() { DB::unprepared('DROP TRIGGER `add_employees_salary`'); } }
php artisan migrate