Restrict Access to Admins In Laravel

By | 18th November 2017

I wanted to be able to have users and admins use the same login form and the admins have the same access as the users but with certain parts of the site only for admins without having to create a new table in the database as well.

Edit Database Migration

Firstly we are going to modify the current users table and and add some code to made this work.

We are going to modify the database migration file and add check_admin column. If check_admin column is true it would allow the user access to admin only page, if check_admin had a value of false it would redirect the user.

Create Middleware

Now we need to create the middleware and it’s very easy to do using php artisan make:middleware CheckPermission. This will create a file in \app\Http\Middleware. We then add some code as you can see below within the handle function to check if the user is a admin, if so we allow the user access to the page, if not we redirect.

Adding Code To The Kernal

To made this work we need to add our middleware to the kernal right under the default web group. You will find the kernal file in App\Http

How To Use

Now admins should only be able to access the example page below, if you want to only allow admins access a certain page you can add ->middleware(‘admin’); to the end of the route.