Courses

Laravel 12 Multi-Tenancy: All You Need To Know

Event System: Delete Database when Deleting Tenant

Summary of this lesson:
- Implementing tenant deletion with event system
- Managing database cleanup through event pipelines
- Handling cascading deletions across tenant resources

Next, I want to demonstrate the power of event system in the stancl/tenancy package. We have seen an example earlier in this course when creating a database and migrating tables when a tenant is created. You can listen to an event and have a lot of classes executed on that event.


In the TenantServiceProvider, we have already seen a job pipeline when a tenant is being created.

app/Providers/TenantServiceProvider.php:

class TenancyServiceProvider extends ServiceProvider
{
// By default, no namespace is used to support the callable array syntax.
public static string $controllerNamespace = '';
 
public function events()
{
return [
// Tenant events
Events\CreatingTenant::class => [],
Events\TenantCreated::class => [
JobPipeline::make([
Jobs\CreateDatabase::class,
Jobs\MigrateDatabase::class,
// Jobs\SeedDatabase::class,
 
// Your own jobs to prepare the tenant.
// Provision API keys, create S3 buckets, anything you want!
 
])->send(function (Events\TenantCreated $event) {
return $event->tenant;
})->shouldBeQueued(false), // `false` by default, but you probably want to make this `true` for production.
],
Events\SavingTenant::class => [],
Events\TenantSaved::class => [],
Events\UpdatingTenant::class => [],
Events\TenantUpdated::class => [],
Events\DeletingTenant::class => [],
Events\TenantDeleted::class => [
JobPipeline::make([
Jobs\DeleteDatabase::class,
])->send(function (Events\TenantDeleted $event) {
return $event->tenant;
})->shouldBeQueued(false), // `false` by default, but you probably want to make this `true` for production.
],
 
// ...
];
}
 
// ...
}

Now, let's try to delete the tenant and see what happens. We have an event, TenantDeleted, and then...

The full lesson is only for Premium Members.
Want to access all 22 lessons of this course? (88 min read)

You also get:

  • 73 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord