Published on

Add subdomain with main domain in laravel project


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

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

so now Domain.php will looks like this


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. '))
       return $next($request);

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

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

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

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


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 () {

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

on you will serve home page and on you will get 404