Alex Sears

Adding Roles to Laravel Users

Introduction

user

Alex Sears

Developer. Drummer. Ginger.


article

Adding Roles to Laravel Users

Posted by Alex Sears on .
Featured

article

Adding Roles to Laravel Users

Posted by Alex Sears on .

The one thing I love about Symfony2 over Laravel is the built in system Symfony has for creating roles. For those of you who don’t understand what I mean by roles, roles allow a developer to bar parts of an application off from users who don’t need access.

A good example of this is WordPress’ Roles and Capabilities. Adding roles to Laravel is a necessity for most applications. Below is my implementation for a project I worked on recently.

The Database

First, we have to create the database tables to use. Migrations to the rescue! We need three tables: users, roles, and user_roles. The user_roles is a “pivot table” for accessing the many-to-many relationship between a user and its roles.

Users Table

 1 <?php
 2 
 3 use Illuminate\Database\Schema\Blueprint;
 4 use Illuminate\Database\Migrations\Migration;
 5 
 6 class CreateUsersTable extends Migration
 7 {
 8 
 9     /**
10      * Run the migrations.
11      *
12      * @return void
13      */
14     public function up()
15     {
16         Schema::create(
17             'users',
18             function (Blueprint $table) {
19                 $table->increments('id');
20                 $table->string('email', 50);
21                 $table->string('password', 60);
22                 $table->string('first_name', 50);
23                 $table->string('last_name', 50);
24                 $table->string('city', 100)->nullable();
25                 $table->string('state', 2)->nullable();
26                 $table->string('phone', 12)->nullable();
27                 $table->integer('points')->nullable();
28                 $table->timestamps();
29             }
30         );
31     }
32 
33     /**
34      * Reverse the migrations.
35      *
36      * @return void
37      */
38     public function down()
39     {
40         Schema::drop('users');
41     }
42 
43 }

Roles Table

 1 <?php
 2 
 3 use Illuminate\Database\Schema\Blueprint;
 4 use Illuminate\Database\Migrations\Migration;
 5 
 6 class CreateRolesTable extends Migration
 7 {
 8 
 9     /**
10      * Run the migrations.
11      *
12      * @return void
13      */
14     public function up()
15     {
16         Schema::create(
17             'roles',
18             function (Blueprint $table) {
19                 $table->increments('id');
20                 $table->string('name');
21             }
22         );
23     }
24 
25     /**
26      * Reverse the migrations.
27      *
28      * @return void
29      */
30     public function down()
31     {
32         Schema::drop('roles');
33     }
34 
35 }

User_Roles Table

 1 <?php
 2 
 3 use Illuminate\Database\Schema\Blueprint;
 4 use Illuminate\Database\Migrations\Migration;
 5 
 6 class CreateUsersRolesTable extends Migration
 7 {
 8 
 9     /**
10      * Run the migrations.
11      *
12      * @return void
13      */
14     public function up()
15     {
16         Schema::create(
17             'users_roles',
18             function (Blueprint $table) {
19                 $table->integer('user_id');
20                 $table->integer('role_id');
21             }
22         );
23     }
24 
25     /**
26      * Reverse the migrations.
27      *
28      * @return void
29      */
30     public function down()
31     {
32         Schema::drop('users_roles');
33     }
34 
35 }

The Models

Now we need to add some code in our models so Laravel understands the relationship between a user and its roles. We will also add a couple functions to make interacting with a user’s roles super easy!

The User

 1 <?php
 2 use Illuminate\Auth\UserInterface;
 3 use Illuminate\Auth\Reminders\RemindableInterface;
 4 
 5 class User extends BaseModel implements UserInterface, RemindableInterface
 6 {
 7     /**
 8      * Get the roles a user has
 9      */
10     public function roles()
11     {
12         return $this->belongsToMany('Role', 'users_roles');
13     }
14 
15     /**
16      * Find out if User is an employee, based on if has any roles
17      *
18      * @return boolean
19      */
20     public function isEmployee()
21     {
22         $roles = $this->roles->toArray();
23         return !empty($roles);
24     }
25 
26     /**
27      * Find out if user has a specific role
28      *
29      * $return boolean
30      */
31     public function hasRole($check)
32     {
33         return in_array($check, array_fetch($this->roles->toArray(), 'name'));
34     }
35 
36     /**
37      * Get key in array with corresponding value
38      *
39      * @return int
40      */
41     private function getIdInArray($array, $term)
42     {
43         foreach ($array as $key => $value) {
44             if ($value == $term) {
45                 return $key;
46             }
47         }
48 
49         throw new UnexpectedValueException;
50     }
51 
52     /**
53      * Add roles to user to make them a concierge
54      */
55     public function makeEmployee($title)
56     {
57         $assigned_roles = array();
58 
59         $roles = array_fetch(Role::all()->toArray(), 'name');
60 
61         switch ($title) {
62             case 'super_admin':
63                 $assigned_roles[] = $this->getIdInArray($roles, 'edit_customer');
64                 $assigned_roles[] = $this->getIdInArray($roles, 'delete_customer');
65             case 'admin':
66                 $assigned_roles[] = $this->getIdInArray($roles, 'create_customer');
67             case 'concierge':
68                 $assigned_roles[] = $this->getIdInArray($roles, 'add_points');
69                 $assigned_roles[] = $this->getIdInArray($roles, 'redeem_points');
70                 break;
71             default:
72                 throw new \Exception("The employee status entered does not exist");
73         }
74 
75         $this->roles()->attach($assigned_roles);
76     }
77 }

First, we have a function that determines whether someone is an “employee” (the application this was made for determined the name). Next is a function that when supplied with a role, it will determine if the user has that particular capability (or role). Then we have a helper function that will return the id number of the value that is supplied. This is used in our last function. This function allows you to pass the “title” the person should have. Each title corresponds with a certain group of permissions, each building on each other. Therefore, the title with the most permissions is at the top of the switch statement. This function will need to be edited depending on the roles your application requires.

The Role

 1 <?php
 2 
 3 class Role extends Eloquent
 4 {
 5     /**
 6      * Set timestamps off
 7      */
 8     public $timestamps = false;
 9 
10     /**
11      * Get users with a certain role
12      */
13     public function users()
14     {
15         return $this->belongsToMany('User', 'users_roles');
16     }
17 }

How to Use Roles

If you wanted to check if a user should have access to a specific area, you can write something like this.

1 <?php if ( $user->hasRole('edit_customer') ) /* Do something epic! */; ?>

Say you wanted to create a new user and then give them admin access, you could write something like the following code.

 1 <?php
 2 $user = User::create(
 3             array(
 4                  'first_name' => 'Alex',
 5                  'last_name'  => 'Sears',
 6                  'password' => 'Cincinnati',
 7                  'email' => 'alexsears@gmail.com',
 8                  'city' => 'Cincinnati',
 9                  'state' => 'OH'
10             ));
11         $user->makeEmployee('admin');
12 ?>

Lastly, we can check if a user is an employee (has some roles) by calling the isEmployee function on the user.

1 <?php if ( $user->isEmployee() ) /* Do something even more epic! /*; ?>

Wrapping Up

I hope this helps anyone who is having troubles with roles in Laravel finds this helpful. I’m hoping to refine this technique and make it available as a package. As always, let me know what you think. Post any comments below!

Further Reading

user

Alex Sears

http://alexsears.com

Developer. Drummer. Ginger.