1

I set a database connection by the auth()->user()-dbname This works as desired using this in the model

public function __construct() {
    $this->connection = auth()->user()->dbname;
}

Now I want to observe the model on creation, update, etc. I tried to use

protected static function boot()
{
    parent::boot();

    static::creating(function ($model) {
        $itemIds = $model->item_ids;
        ... update another model based on the $itemIds            
    });

But Nova is not recognizing the static::creating function So I created an Observer (I think a better choice) however when the observer is called it does not recognize the

auth()->user()->dbname property

Why doesn't the observer recognize auth?

dmgd
  • 425
  • 4
  • 15

2 Answers2

0

This may be caused because there is no authenticated user. Try dumping and see what it throws you.

public function __construct() {
    // Should throw an User model OR null. 
    dd(auth()->user());
    // Alternatively, you could use the Logger
    \Log::info(json_encode(auth()->user()));
    $this->connection = auth()->user()->dbname;
}

If auth()->user() is null, then no user is logged in and as you might have guessed, null is a non-object.

IGP
  • 14,160
  • 4
  • 26
  • 43
  • Thanks this returns null when using an observer otherwise it works as desired. But the boot method in the model is ignored. – dmgd Aug 02 '19 at 21:43
  • I'm not sure if it's relevant to you but I had similar troubles setting up an Observer that kept throwing errors in the seeding stages because no user was actually logged in. In the end, I had to [use the Request to discern if an user or the console (symfony) was behind the model updates](https://stackoverflow.com/questions/56069090) – IGP Aug 02 '19 at 22:09
0

Thanks for the suggestions but none would work for me. I gave up on Observers in Nova. I used the boot() function. This is how I setup milti tenant.

In the _constructor I added this

public function __construct() {
    parent::__construct(); // needed before boot would fire
    $this->connection = auth()->user()->dbname;
 }

Then my boot() function became the observer

   protected static function boot()
    {
        parent::boot();

        static::creating(function($item) {
             $item->event_id = Event::currentEventID();

        });
    }
dmgd
  • 425
  • 4
  • 15