Simplistic Role Systems

Laravel Tidbits

In this lesson we learn how to create a simplistic role system that will allow for guest, members, subscribers and administrators to access specific routes.

Video Information

Hi everyone, welcome back to Laracademy. In this video we are going to be going over a simplistic role system. Our system will contain four different roles. We will have an administrator, a subscriber, a member and finally a guest.

The different between a subscriber and member is the user has subscribed to a service that you are offering by either paying, or you gave them an account.

Now there are a lot of role packages out there and in the future I plan on covering a few, and also a different technique but for now let's take a very simple approach to this. We are going to be modifying the user table to help us with this. We will also utilize a middleware to restrict users from certain pages when needed.

First let's write a database migration to alter the user's table.

php artisan make:migration alter_user_table_add_roles --table=users

Now let's open up our migration and alter the table

$table->boolean('subscriber')->default(false)->after('password');
$table->boolean('administrator')->default(false)->after('subscriber');

Next let's run our migrations.

php artisan migrate

Since we changed some fields in our user table, lets update our model's fillable fields.

protected $fillable = [
  'name',
  'email',
  'password',
  'subscriber',
  'administrator',
]

Since we are using booleans, let's tell Laravel to cast our values into a true or false value.

protected $casts = [
  'subscriber' => 'boolean',
  'administrator' => 'boolean',
]

Now I already went ahead and created a database seeder, if we take a quick look you can see I am basically just creating 3 different users. We have a member, a subscriber and an administrator.

I have already created some routes for these users. If we look at the web.php route file you can see we have 4 routes defined for this purpose. We have a guest route that can be accessed by everyone, a member route that will be allowed only to a member, subscriber or administrator. We also have a subscriber route that will allow a subscriber and administrator and finally an administrator route.

We can use what is called Middleware to restrict users based on what we want. By default everyone is allowed in our routes, so for the guest route we dont need to do anything. Laravel comes with an "authenticated" middleware. This means the user needs to be logged in so we can append this middleware on to this route to only allow users who are signed up to view our page.

Route::get('member')->uses('MemberController@index')->middleware('auth');

Now if we try to access this route, you can see we will not be allowed. Let's login with one of our users, specifically the member role. We will be using a simple route to help us.

Route::get('login/{id}', function($id) {
  $user = \App\User::find($id);
  auth()->login($user);

  return 'You are logged in as '. $user->name;
});

Route::get('logout', function() {
  auth()->logout();

  return 'You are now logged out';
});

With this user we can access the /guest and our /member route. Okay, but what about our "subscriber" route. Currently we have no problem accessing it. So let's create a middleware.

php artisan make:middlware SubscriberOnly

Now we can open up our middleware in app/Http/Middleware

<?php

namespace App\Http\Middleware

use Closure;

class SubscriberOnly
{
  public function handle(request, CLosure $next)
  {
    $isSubscriber = false;

    if(auth()->check()) {
      if(auth()->user()->subscriber) {
        $isSubscriber = true;
      }
    }

    if(! $isSubscriber) {
      // not a subscriber
      return redirect('/');
    }

    return $next($request);
  }
}

Now let's register our middleware by opening up our kernel.php.

'subscriber' => \App\Http\Middleware\SubscriberOnly::class,

Finally we can add it to our route, and give it a try with our member user.

Route::get('subscriber')->uses('SubscriberController@index')->middleware('subscriber')

Now that everything works we have a slight problem. If we log in with our administrator you will see that we cannot access our subscriber route. Let's quickly edit our middleware to take care of that.

if(auth()->check()) {
  if(auth()->user()->subscriber) {
    $isSubscriber = true;
  }
  else if(auth()->user()->administrator) {
    $isSubscriber = true;
  }
}

Now let's test this route again with our administrator.

Finally we need to create an administrator middleware.

php artisan make:middleware AdministratorOnly

This one will be pretty simple and close to what we have already written.

<?php

namespace App\Http\Middleware

use Closure;

class AdministratorOnly
{
  public function handle(request, CLosure $next)
  {
    $isAdministrator = false;

    if(auth()->check()) {
      if(auth()->user()->administrator) {
        $isAdministrator = true;
      }
    }

    if(! $isAdministrator) {
      // not a subscriber
      return redirect('/');
    }

    return $next($request);
  }
}

Now let's register this middleware so that we can use it

'administrator' => \App\Http\Middleware\AdministratorOnly::class,

And let's assign it to our administrator route.

Route::get('administrator')->uses('AdministratorController@index')->middleware('administrator')

Now let's load up chrome and see if we can get to this route as an administrator. We will also log out and try it as a subscriber, a member and finally as a guest.

Do you have a question? Go ahead and ask it below.

Please login to ask your question