Sunday, 13 November 2016

Laravel 5 mysql trigger from migration

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.

Trigger in Laravel


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

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts