Technical notes about OctoberCMS a Laravel CMS. Notes are written by inetis team, a Swiss webagency

Did you manage multiple websites? Try our OctoberCMS monitoring solution

<- Back

Add extra fields to User model or other model

Posted on by

Sometime you need to add extra fields to a model.

Sometime you need to add extra fields to a model. You will find the official documentation here : https://octobercms.com/docs/plugin/extending#extending-user-mode

I prefer using an external YAML file to configre my extra fields and keep Plugin.php small.

    public function boot()
    {
        $this->registerUserExtraFields();
    }

   private function registerUserExtraFields()
    {
        $userFields = Yaml::parseFile(__DIR__ . '/models/users/custom_fields.yaml');

        UserModel::extend(function (UserModel $model) use ($userFields) {
            $model->addFillable(array_keys($userFields));
        });

        UsersController::extendFormFields(function (Form $widget) use ($userFields) {
            // Prevent extending of related form instead of the intended User form
            if (!$widget->model instanceof UserModel) {
                return;
            }
            $widget->addTabFields($userFields);
        });
    }

Create a YAML file in myplugin/models/users/custom_fields.yaml with your fields

fielda:
    label: Field A
    type: text
    span: auto
    tab: MyTab
fieldb:
    label: Discount B
    type: text
    span: auto
    tab: MyTab