Search code examples
phplaraveloctobercmslaravel-notification

OctoberCMS: How to make the User model notifiable?


The RainLab\User\Models\User class does not use the Notifiable trait and therefore it's not possible to call notify or Notification::send on it. I want to write a plugin that extends the RainLab\User\Models\User and adds Notifiable trait to it. How can I do this?


Solution

  • I've implented the trait as a behavior: https://github.com/CptMeatball/notifiable-user

    How does it work?

    This plugin acts as a simple wrapper for the Notifiable trait and adds this as a behavior to the User model. It works by inserting the trait inside the behavior class. It then gets added to the User model during the boot method of the plugin. Simple as that.

    NotifiableBehavior

    use Illuminate\Notifications\Notifiable as NotifiableTrait;
    class Notifiable extends \October\Rain\Database\ModelBehavior
    {
        use NotifiableTrait;
        public function __call($name, $params = null)
        {
            if (!method_exists($this, $name) || !is_callable($this, $name)) {
                return call_user_func_array([$this->model, $name], $params);
            }
        }
    }
    

    Plugin.php

    public function boot()
    {
        User::extend(function($model) {
            $model->implement[] = 'CptMeatball.NotifiableUser.Behaviors.Notifiable';
        });
    }
    

    You can use the same principle for any other trait.