Published on

Add subdomain with main domain in laravel project

Authors

Let's use the subdomain in a single laravel application with the main domain. as it looks complex but it's not, follow the below steps,

we will create middleware to avoid view main domain parts in the subdomain and vice versa.

Step 1: Create middleware Run below command

$ php artisan make:middleware Domain

It'll create middleware file in app/Http/Middlewares with name of Domain.php

Step 2: Update config file add config in app.php with domain name

which looks like this

app.php
...
'url' => env('APP_URL', 'http://localhost'),
'domain' => env('APP_DOMAIN', 'localhost'),
...

so now Domain.php will looks like this

Domain.php
<?php    

namespace AppHttpMiddleware;

use Closure;

class Domain
{
    /**
     * Handle an incoming request.
     *
     * @param IlluminateHttpRequest $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->getHost() != config('app. '))
            abort(404);
       return $next($request);
    }
}

here config('app.domain') is my main domain name like example.com

Step 3: Update the kernel.php add middleware in Http Kernel file which is located at app/Http/Kernel.php

find protected $routeMiddleware array list, and add on top of the list

which will look like this

Kernel.php
protected $routeMiddleware = [
    'domain' => AppHttpMiddlewareDomain::class,
    'auth' => AppHttpMiddlewareAuthenticate::class,
    'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
    'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
    'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
    'can' => IlluminateAuthMiddlewareAuthorize::class,
    'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
    'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
    'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
    'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
    'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
];

Step 4: Add middleware to web.php

now you can use your middleware in web.php like this

web.php
...
Route::middleware(['domain'])->group(function () {
    Route::get('/', 'PageController@home_page')->name('home');
});
...

or

web.php
...
Route::get('/', 'PageController@home_page')->name('home')->middleware('domain');
...

For example, your web.php has something like this

...
Route::domain('app.'.config('app.domain'))->group(function () {
    Route::get('/dashboard', function () {
        dd('Dashboard');
    });
});

Route::middleware(['domain'])->group(function () {
    Route::get('/', 'PageController@home_page')->name('home');
});
...

on http://example.com you will serve home page and on http://app.example.com you will get 404