One way to achieve this is to use middleware to check the subdomain and redirect the user if necessary. Here's an example:
- Create a middleware class that checks the subdomain and redirects the user if necessary:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectSubdomain
{
public function handle($request, Closure $next)
{
$subdomain = $request->route('subdomain');
$user = Auth::user();
if ($user && $user->subdomain !== $subdomain) {
return redirect()->route('home', ['subdomain' => $user->subdomain]);
}
return $next($request);
}
}
This middleware checks if the authenticated user's subdomain matches the subdomain in the URL. If they don't match, it redirects the user to their own subdomain.
- Register the middleware in your
Kernel.phpfile:
protected $routeMiddleware = [
// ...
'subdomain' => \App\Http\Middleware\RedirectSubdomain::class,
];
- Apply the middleware to your routes:
Route::group(['middleware' => 'subdomain'], function () {
// your routes here
});
This will ensure that the middleware is applied to all routes in the group.
- When a user logs in, store their subdomain in the session:
public function login(Request $request)
{
// authenticate the user
// ...
session(['subdomain' => $user->subdomain]);
return redirect()->route('home', ['subdomain' => $user->subdomain]);
}
This stores the user's subdomain in the session and redirects them to their own subdomain.
- Finally, update your routes to include the subdomain parameter:
Route::group(['domain' => '{subdomain}.example.com'], function () {
// your routes here
})->where('subdomain', '[a-z0-9]+');
This will capture the subdomain from the URL and pass it to your routes.
With these changes, your application should automatically redirect authenticated users to their own subdomain.