Restrict Access to Admins In Laravel

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

<?php

useIlluminate\Support\Facades\Schema;

useIlluminate\Database\Schema\Blueprint;

useIlluminate\Database\Migrations\Migration;

classCreateUsersTableextendsMigration

{

/**

* Run the migrations.

*

* @return void

*/

publicfunctionup()

{

Schema::create('users',function(Blueprint$table){

$table->increments('id');

$table->string('email')->unique();

$table->string('username')->unique();

$table->boolean('check_admin')->default('false');

$table->string('password');

$table->rememberToken();

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

publicfunctiondown()

{

Schema::dropIfExists('users');

}

}

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

<?php

namespaceApp\Http\Middleware;

useClosure;

useIlluminate\Support\Facades\Auth;

classCheckPermission

{

/**

* Handle an incoming request.

*

* @param \Illuminate\Http\Request $request

* @param \Closure $next

* @return mixed

*/

publicfunctionhandle($request,Closure$next,$guard=null)

{

if(Auth::guard($guard)->guest()){

if($request->ajax()){

returnresponse('Unauthorized.',401);

}else{

returnredirect()->guest('login');

}

}elseif(!Auth::guard($guard)->user()->check_admin){

returnredirect()->to('/')->withError('Denied Access');

}

return$next($request);

}

}

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