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:

Run below command

php artisan make:middleware Domain

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

step 2:

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

<?php

namespace App\Http\Middleware;

use Closure;

class Domain
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $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:

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' => \App\Http\Middleware\Domain::class,
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];

step 4:

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

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

or

...
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

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.