How to Create Custom Routes for protected Admin/Manager area in Laravel 8

In my last article I showed you How to Create Custom Route File in Laravel 8. In that article I created an admin custom routes which is accessible at http://127.0.0.1:8000/admin. In this articles I will show you how you can place custom check for user type to protect your admin routes. I will use middleware named admin to achieve custom routes protection.

Creating Admin Custom Routes and protect via Middleware in Laravel

Perquisite: An installed and working Laravel Application

Generally you would have a Laravel app with users table which you would use to authenticate users into your application. To authenticate you would use Laravel’s inbuilt Authorization(\Illuminate\Auth\Middleware\Authorize), or in short, the Auth mechanism along with web routes. I hope and expect that you already have knowledge of Auth and web routes and would suggest that discussing it here is out of scope.

So generally you would have a http://127.0.0.1:8000/login or similar web route which you use to login into your web application. We will extend app to have a http://127.0.0.1:8000/admin area and limit access to it to the users who have is_admin or similar flag set.

Creating Admin Custom Routes and protect via Middleware

In order to create protected custom routes I would create a new boolean field is_admin in the users table. Once user logs in and if it is found to be set to true, I would allow user to visit http://127.0.0.1:8000/admin. Otherwise I would send them to some other screen such as login screen.

Let’s do it now.  (You would already have done most of the steps in previous articles if you did read it ever 😊 )

Create a file routes/admin.php with the following code:

use App\Http\Controllers\UsersController;
use Illuminate\Support\Facades\Route;
use Illuminate\Routing\Router;
use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| Admin Routes
|--------------------------------------------------------------------------
|
| Here is where you can register admin routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "admin" middleware group. Now create something great!
|
*/

Route::get('/', function() {
    print('I am an admin');
});

Next, open the app/Providers/RouteServiceProvider.php and find public function boot() in it. Add the following code to it, just above or below the existing lines of code for web and api routing.

Route::prefix('admin')
->namespace($this->namespace)
->group(base_path('routes/admin.php'));

So it becomes:

    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));

            Route::prefix('admin')
                ->middleware(['web', 'admin'])
                ->namespace($this->namespace)
                ->group(base_path('routes/admin.php'));
        });
    }

You should see I am an admin message on your browser window at http://127.0.0.1:8000/admin.

In order to limit access to it we will use a middleware named Admin. You can name it to anything you want.

Create a file app/Http/Middleware/Admin.php with the following code:

namespace App\Http\Middleware;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Closure;

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
    }
}

Next, let put some code inside handle function to filter requests for users.

namespace App\Http\Middleware;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Closure;

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::user() && Auth::user()->is_admin) {
            return $next($request);
        }
        return redirect()->route('login');
    }
}

The code is quite obvious but I will still explain it a bit. Inside the handle function we are checking whether user session exists and if it does continue with current request. If it does not it will redirect user to login screen.

Next, inject your new middleware Admin to $routeMiddleware array in Kernel.php file.

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

Last but not least. Add your new middleware Admin to the END of $middlewarePriority array in Kernel.php file.

    protected $middlewarePriority = [
        \Illuminate\Session\Middleware\StartSession::class,
        ........
        \App\Http\Middleware\Admin::class,
    ];

NOTE: Admin middleware must be injected after the StartSession class call in $middlewarePriority array, otherwise IT WONT work. Failing to do so the Auth::user() would return null resulting in a failure of all the effort we did so far!

I hope you like this article. Do comment.

Leave a Reply