Add simple Admin Middleware in your Laravel App

Photo by Mohammad Rahmani on Unsplash

In most of the Laravel application, we have some admin only section or endpoints to manage our site and this section can be accessed by admins only.

In order to protect this admin section from normal users we need some sort of authorisation that will check if a user is allowed to this section or not. There are may ways to achieve this.In this post, we are going to use Laravel Middleware to restrict this access to admin only.

First of all, how do we check if a user is admin or not. If you have only one admin, you can simply check if this user email or username is same as admin email or username. Or if your application has more than one admin, you can add a new column role to users table.

Now let’s add a method to our User model class that will return if the user is an admin or not.

OR check against email

For admin users this isAdmin() method will return true and for normal user, this will return false. Now moving to the next part, we will create a IsAdmin middleware that will allow only admin users to access the application.

To create a middleware, you can use following command —

This will create a middleware file app/Http/Middleware/IsAdmin.php

In handle method of IsAdmin.php middleware file, we will check if request user is admin or not. If the user is not a admin user, will abort the request and return. So our middleware will look like this —

You can update this handle method according to your application. The thing to remember here is, you call $next() callback only for admin users. If the user is not admin, you abort and return.

Now of middleware is ready, we can register this middleware to our application. To register, add this to `$routeMiddleware` array of app/Http/Kernel.php with key as admin

Now our middleware is registered and we can use it to restrict admin access to our application. There are many ways you can use this middleware. Here we are going to use this with routes.

In routes, you may use the middleware method to assign middleware to a route:

Now or /admin/users route is protected and only admin users can access this. To read more about Laravel middlewares, check the official docs at https://laravel.com/docs/8.x/middleware

--

--

Web Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store