How to use triggers in laravel?

HARIKRISHNA picture HARIKRISHNA · Mar 6, 2019 · Viewed 9.4k times · Source

My code, using PHP artisan make: migration create_trigger command

public function up()
{
  DB::unprepared(' 
  CREATE TRIGGER roll_no BEFORE INSERT ON `students` FOR EACH ROW 
  BEGIN 
  SET @roll_num = IFNULL((substring((SELECT student_roll_no FROM students WHERE
    class_code = NEW.class_code ORDER BY created_at DESC LIMIT 1),-2) + 1), `1`),
    NEW.student_roll_no = CONCAT(
    YEAR(CURRENT_DATE),
    NEW.class_code,
    IF (@roll_num < 10, CONCAT(`0`, @roll_num), @roll_num) 
  )
  END;
  ');
}

Answer

hoseinz3 picture hoseinz3 · Mar 6, 2019

You don't need to create a migration for a model event. Laravel eloquent has multiple events such as retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored that you can easily use them.

first, you should create Observer for your model like this

php artisan make:observer UserObserver --model=User

in the UserObserver you can listen to any event that you like such as:

class UserObserver
{
    /**
     * Handle the User "created" event.
     *
     * @param  \App\User  $user
     * @return void
     */
    public function created(User $user)
    {
        //
    }

    /**
     * Handle the User "updated" event.
     *
     * @param  \App\User  $user
     * @return void
     */
    public function updated(User $user)
    {
        //
    }
}

after that you should register your observer to model in app/providers/AppServiceProvider boot method such as:

public function boot()
{
     User::observe(UserObserver::class);
}

for more detail visit Laravel documentation.