October CMS : How to extend User class to add relationship?

1.2k views Asked by At

Hello there i'm new to October CMS and i just started with User class What i know i create relationship in laravel is so easy.

I have extended user plunging.

    User::hasCountry()->get();

    public hasCountry($query){
        return $query->where('country',1);
    } 

SO i have created this relation but i dont know how to add into Extended User class.

I have found one solution

public function boot()
{
    User::extend(function($model) {
        $model->addDynamicMethod('hasCountry', function($query) {
            return $query->where('country', 1);
        });
    });
}

But it is not extending or adding methode.

Please Help :)

1

There are 1 answers

0
David Lundquist On

I read the suggested approach. If I understand it correctly, this idea would alter the Code Base for the OctoberCMS install, which is not ok and could cause havoc when new October Updates are pushed to your app.

Why not just create a new Model using the backend_user table and then add all the relationships you want?

Example:

use Model;

/**
 * Model
 */
class EnhancedUser extends Model
{
   /**
   * @var string The database table used by the model.
   */
  public $table = 'backend_users';       

  public $hasOne = [
        'Country' => 'Acme\Blog\Models\Country' //path of your country model
    ];
 }

I believe the right way to add functionality to your App with OctoberCMS is to create a custom plugin, and IMO that would seem to offer the most flexability.

If you need to get your current User to base an instance of your EnhancedUser Model use this:

BackendAuth::getUser(); //Returns the authenticated user

BTW: I found these resources great when learning to build custom plugins for OctoberCMS:

  1. (My personal fav and The Lazy Man's Way). Install the "Builder" plugin and then go here and watch the [How To] Video:

    Plugin: http://octobercms.com/plugin/rainlab-builder

    Video: https://vimeo.com/154415433

  2. The Docs http://octobercms.com/docs/plugin/registration