Member-only story
A full-featured multi-tenant app with Laravel Part 4 —Tenancy aware Authentication.
Part 0, Part 1, Part 2, Part3, Part4 👇, Part 5, Part 6, Part 7
In this part of writing a complete Laravel multi-tenant app series, we’ll accomplish the following task:
✅ Make Laravel out-of-the-box authentication scaffolding work with tenancy
In the last post, we made our app send out an email inviting the admin to set the password. Everything seemed to be working except for the password submission part where it threw an error saying it couldn’t find the password_resets table. But if you check the database, it’s already there!
The problem is that Laravel built-in routes for Auth, which you will find in your routes/web.php file, is not aware of tenancy and tries to look into the system/master database instead of the tenant’s database. So, to make it work, we just have to “enforce” the database connection for this route and that’s it!
There are a number of ways to resolve it but we’ll use one solution that is easy and elegant — using a Laravel middleware. I’ve already used this in a live production app and so far it seems to be working fine. So if it works, is easy and elegant, why the heck not right? Let’s do it!
1. Create a middleware
php artisan make:middleware EnforceTenancy
Open app/Http/Middlware/EnforceTenancy.php file and make it like so:
The most (and only) important line here is #12. We just “enforced” to use ‘tenant’ connection whenever this middleware is applied. This is the database connection used by Tenancy package by default for all tenants.
2. Apply middleware
First, we have to register this middleware in app/Http/Kernel.php file as tenancy.enforce:
...protected $routeMiddleware = [
...
'tenancy.enforce' => \App\Http\Middleware\EnforceTenancy::class
];...