Summer Sale! All accounts are 50% off this week.

maytham's avatar

Creating Triggers from Migration

I have created stored procedure from migration it works just fine.

DB::unprepared('
        CREATE PROCEDURE sp_Task_Default(IN _kid_id INT)
        BEGIN
            INSERT INTO tasks (kid_id, name) VALUES (_kid_id, \'Default\');
        END
        ');

Now I have tried to create Trigger with following code

DB::unprepared('
        CREATE TRIGGER tr_Task_Default AFTER INSERT ON kids FOR EACH ROW
        BEGIN
            INSERT INTO tasks (kid_id, name) VALUES (NEW.id, \'Default\');
        END
        ');

It return with this error after I run php artisan migrate

{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class 'CreateTriggers' not found","file":"C:\\xampp\\htdocs\\dev03\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Migrations\\Migrator.php","line":301}}
Process finished with exit code 255 at 22:01:59.
Execution time: 239 ms.

Any tips, what is going wrong? appreciated

0 likes
5 replies
maytham's avatar
maytham
OP
Best Answer
Level 3

Solved now, there was issues with class naming,

I delete the migration file and generate new one

php artisan generate:migration create_trigger

After it was generated I copy and paste the same code and it works just fine, some time when you work late, you pay a good price.

Here is the final working code for creating trigger through migration.

it works both with RAW and UNPREPARED method.

<?php

use Illuminate\Database\Migrations\Migration;

class CreateTrigger extends Migration {

 public function up()
 {

        DB::unprepared('
        CREATE TRIGGER tr_User_Default_Member_Role AFTER INSERT ON `users` FOR EACH ROW
        BEGIN
         INSERT INTO role_user (`role_id`, `user_id`, `created_at`, `updated_at`) VALUES (3, NEW.id, now(), null);
        END
        ');
 }


 public function down()
 {
  DB::unprepared('DROP TRIGGER `tr_User_Default_Member_Role`');
 }

}


2 likes
barkingsand22's avatar

just curious about the artisan command used here, "php artisan generate:migration create_trigger" Does artisan support a generate:migration command?

andreportaro's avatar

As of 5.2, the command should be php artisan make:migration migration_name.

mantu's avatar

php artisan generate:migration create_trigger Artisan Command Not Working.

asqarrsl's avatar

php artisan make:migration create_trigger

This will work

Please or to participate in this conversation.