How to add mysql trigger from migrations in Laravel?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Sometimes we need to add trigger in our mysql database of laravel . but we think how to create the trigger by using laravel migration because laravel not provide any special function as like insertTrigger and also something so it is a problem to create direclty, But laravel DB::unprepared() through we can also create trigger for database.

So now in following example we can see how to create migration and need to create a trigger code and how to write drop the trigger code, so let’s do it this way.

Create Migration:
php artisan make:migration add_trigger
Migration:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddTrigger extends Migration
{
    public function up()
    {
        DB::unprepared('CREATE TRIGGER add_Item_city AFTER INSERT ON `items` FOR EACH ROW
                BEGIN
                   INSERT INTO `items_city` (`item_id`) VALUES (NEW.id);
                END');
    }
    public function down()
    {
        DB::unprepared('DROP TRIGGER `add_Item_city`');
    }
Run Migration:
php artisan migrate

Read Also :Laravel Join with Subquery in Query Builder Example

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →