spatie/laravel-multitenancy

3.0.2 crashes on using dispatchSync() with database transactions

slavatarsyurimi opened this issue · 6 comments

Previously there has been a discussion about using database transactions when using different databases per tenant #371.
Using DB::connection('tenant')->transaction(...) seems logical enough. However, version 3.0.2 introduced a breaking change in one of our projects, so I think this might be worth taking another look at.

I've created a little test repo to demonstrate the issue.

git clone git@github.com:MSMLBV/spatie-multitenancy-issue.git
cd spatie-multitenancy-issue
cp .env.example .env
composer install
php artisan migrate --path=database/migrations/landlord --database=landlord // (this will prompt to create a spatie-mt-issue-landlord) database
php artisan db:seed // this will automatically create 2 databases
php artisan tenant:artisan "migrate"
php artisan user:create

You can observe that the command crashes when passing a model to a job using dispatchSync() in a database transaction.
You can also observe that the issue no longer persists if you downgrade the package to 3.0.1.

I understand that this is easily fixable using DB::connection('tenant')->beginTransaction(); etc, but without extensive knowledge of the package this took quite a while to figure out.
Would it be an idea to add a little piece on using database transactions with multiple tenant databases to the docs?

@slavatarsyurimi I found some issues in your repository.

  1. User model has no UsesTenantConnection trait: you should add it
  2. config/multitenancy.php tenant connection name is empty: you should add tenant
  3. Modify the tenant migrate command like so: php artisan tenant:artisan "migrate --database=tenant"

Now, it will work!

Hi @masterix21, thanks for your reply. I've modified the configuration like you're suggesting: MSMLBV/spatie-multitenancy-issue@df32350

The command php artisan user:create command however still crashes. This time it seems to just be picking the default DB_DATABASE .env database.

   PDOException 

  SQLSTATE[HY000] [1049] Unknown database 'laravel'

Related to #438 (comment)

Hi @masterix21, do have any updates related to this?

Hi,
I have the same problem,
From a tenant context, if we dispatch a NotTenantAware job by using dispatchSync() method, the currentTenant is lost after job is completed processing, and the following code will not be executed (no database selected)

Try again with the release 3.0.3. Thanks!