skip to Main Content

I’m currently working on a Laravel project where I need to set up dynamic subdomains for each user. These subdomains should route requests to individual user profiles and apply middleware for authentication and security. Each user’s subdomain should be generated dynamically.

I’ve explored Laravel’s routing system and middleware, but I’m unsure about creating dynamic subdomains and routing requests to user profiles based on these subdomains. I expected to find a step-by-step guide or code examples that demonstrate how to achieve dynamic subdomain routing with middleware effectively.

2

Answers


  1. To resolve this problem fellow these setps:
    1- Create Middleware:
    Create a custom middleware that checks the subdomain and takes appropriate action. You can generate a middleware using Laravel’s Artisan command:

    php artisan make:middleware SubdomainMiddleware
    

    In the generated middleware, you can check the subdomain from the request and take action accordingly:

    public function handle($request, Closure $next)
    {
        $subdomain = explode('.', request()->getHost())[0];
    
        if ($subdomain === env('SUBDOMAIN')) {
            // Apply middleware logic for this subdomain
        }
    
        return $next($request);
    }
    

    2- Create Routes:
    Define your routes in routes/web.php. You can use Route groups to apply the middleware to specific subdomains:

    Route::group(['middleware' => 'subdomain'], function () {
        // Define routes for your subdomain
        Route::get('/', 'SubdomainController@index');
        // Add more routes here
    });
    

    Apply Middleware to the Route Group:
    In your app/Http/Kernel.php file, add your custom middleware to the $middlewareGroups array:

    protected $middlewareGroups = [
        'web' => [
            // ...
            AppHttpMiddlewareSubdomainMiddleware::class,
        ],
    ];
    

    3- Testing:
    You can test your dynamic subdomain routing by accessing your application with the defined subdomain, such as http://dynamic.example.com.

    Login or Signup to reply.
  2. Instead of middleware you can use built-in subdomain routing and then check if the subdomain exists or not.

    in web.php:

    Route::domain('{account}.example.com')->group(function () {
        Route::get('something/{b}', function (string $account, string $b) {
            if ($account == "foobar") {
                return "ok";
            } else {
                abort(404);
            }
        });
    });
    

    You can expand this for example to check if account exists in database.

    Hopefully this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search