How to change the default Admin URL in Laravel

Configurare noua (How To)

Situatie

By default, Laravel applications use example.com/admin (or a similar route) for the admin dashboard. However, keeping this default URL can expose your site to attacks. Changing it can improve security by making it harder for attackers to find your admin panel.

1. Changing the Admin Route Prefix

Laravel routes are defined in routes/web.php. To change the default admin URL:

Before (Default Admin Route)

Route::get(‘/admin’, [AdminController::class, ‘index’])->name(‘admin.dashboard’);

This makes the admin panel accessible at example.com/admin.

After (Custom Admin Route)

Modify web.php to change /admin to something unique, like /dashboard-secret:

Route::prefix(‘dashboard-secret’)->group(function () {
Route::get(‘/’, [AdminController::class, ‘index’])->name(‘admin.dashboard’);
});

2. Protecting the Admin Route with Middleware

To prevent unauthorized access, apply authentication and role-based middleware:

Update web.php

Route::middleware(['auth', 'admin'])->prefix('dashboard-secret')->group(function () {
Route::get('/', [AdminController::class, 'index']);
});

Ensure Middleware is Set Up

  • auth ensures only logged-in users can access the route.
  • admin is a custom middleware that allows only admin users.

If you don’t have an admin middleware, create one:

php artisan make:middleware AdminMiddleware

Edit app/Http/Middleware/AdminMiddleware.php:

php
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminMiddleware
{
public function handle(Request $request, Closure $next)
{
if (Auth::check() && Auth::user()->is_admin) {
return $next($request);
}
return redirect(‘/’); // Redirect unauthorized users
}
}

Register the middleware in app/Http/Kernel.php:

php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];

Solutie

Tip solutie

Permanent

Voteaza

(3 din 7 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?