lignuss's avatar

Subdomain only for admins

I want to run my application under two subdomains: admin.domain.com and client.domain.com. I want to define centrally that all routes under admin.domain.com can only be accessed by admins. Can you please help me how to define this centrally without having to check this in each controller?

0 likes
4 replies
click's avatar

@lignuss this is a typical job for http Middleware, see: https://laravel.com/docs/9.x/middleware. You can assign middleware to a single route or a group of routes, the documentation explains all of this.

You can create a middleware that checks if the user is an admin or not, if it is not an admin you can redirect them to the client page or show an error message.

If you are not that experienced with middleware, this google search should give you some good answers: https://www.google.com/search?q=laravel+middleware+admin+only

lignuss's avatar

@click Thanks for your answer, I will try to do it this way, it looks good.

MohamedTammam's avatar

Define your routes

// Admin routes
Route::domain('admin.domain.com')->group(function () {
    // Write your admin routes here
})->middleware('admin');

// Client routes
Route::domain('admin.domain.com')->group(function () {
    // Write your client routes here
});
```	
And as @click motioned, you should create your `admin` middleware 	

Subdomain docs: https://laravel.com/docs/9.x/routing#route-group-subdomain-routing
lignuss's avatar

Thanks for your answers! I did now like this:

app/Http/Models/User.php:

    public function isAdmin() {
        ...
    }

app/Http/Middleware/Admin.php:

    public function handle(Request $request, Closure $next)
    {
        if ($request->user()->isAdmin()) {
            return $next($request);
        }
        Session::flush();
        Auth::logout();
        return redirect('login');
    }

app/Http/Kernel.php:

    protected $middlewareGroups = [
...
        'admin' => [
            \App\Http\Middleware\Admin::class
        ],
    ];

routes/web.php:

Route::middleware('auth', 'admin')->group(function () {
    Route::group(['domain' =>'admin.domain.com'], function() {
...
        });
    });
});

It works and I hope it is "correct"

Please or to participate in this conversation.