hipsterjazzbo / Landlord

A simple, single database multi-tenancy solution for Laravel 5.2+
MIT License
612 stars 142 forks source link

Fix querying allTenants when trait on model was not booted yet #75

Open mbaeuerle opened 7 years ago

mbaeuerle commented 7 years ago
rikvdlooi commented 7 years ago

I just experienced this bug as well. It is not a php bug, this is the intended behaviour of Laravel.

  1. If the model is not instantiated the boot() method of the Model will not be called
  2. If the boot() method of the Model has not been called the bootBelongsToTenants() method in BelongsToTenants.php will also not be called

Instantiating the model before calling the newQueryWithoutTenants does indeed fix this, because this will also cause the boot method to be called. :smile:

mbaeuerle commented 7 years ago

Yes it's up to Laravel to boot the trait after an instance of a model was created for the first time but the problem can also arise without Laravel:

<?php
  class A {
    public static $instance;

    public function __construct() {
      static::$instance = new B();
    }

    public static function do() {
      static::$instance->print(new static());
    }
  }

  class B {
    public function print($instance) {
      print("hello");
    }
  }

  A::do(); // Fails with "Fatal error: Uncaught Error: Call to a member function print() on null"
?>

which is working when using the same fix:

$i = new static();
static::$instance->print($i);
rikvdlooi commented 7 years ago

Yep true. Do you think it is beneficial to write an if statement around it. Like first testing if static::$landlord is defined, and otherwise instatializing it?

Also one test is wining about a static call to faker. Should this be fixed or is this fine like it is now?