Create role and permission (Using Entrust) in Laravel

Long time not write blog again, and now I want share how to add permission user using entrust. Okay for the installation, follow the steps below:
First open your laravel project and add this code to your composer:

"require": {
		"laravel/framework": "4.*",
		"barryvdh/laravel-debugbar": "dev-master",
		"zizaco/entrust": "dev-master"

After that, run composer update:

$ composer update

If update succesfully, now open your app.php from your laravel config:

'providers' => array(


And don’t forget to add aliases:

'aliases' => array(

	'App'             => 'Illuminate\Support\Facades\App',
	'Artisan'         => 'Illuminate\Support\Facades\Artisan',
	'Entrust'    	  => 'Zizaco\Entrust\EntrustFacade',

And before to the next step, I assume your laravel already have database connected. This is example my config:

'connections' => array(

	'sqlite' => array(
		'driver'   => 'sqlite',
		'database' => __DIR__.'/../database/production.sqlite',
		'prefix'   => '',

	'mysql' => array(
	    'read' => array(
	        'host' => 'localhost',
	    'write' => array(
	        'host' => 'localhost'
	    'driver'    => 'mysql',
	    'database'  => 'test',
	    'username'  => 'root',
	    'password'  => 'password',
	    'charset'   => 'utf8',
	    'collation' => 'utf8_unicode_ci',
	    'prefix'    => '',

And this is data from my users table:

Then now we must generate the Entrust migration (create file migration for entrust):

$ php artisan entrust:migration

And the we must migrate that file:

$ php artisan migrate

If right, your database have some new table like this:

And now example I use source from latest tutorial from here and I just change litle source and add code for using role and permission in this tutorial.
Okay next we must add Role.php to the models.


use Zizaco\Entrust\EntrustRole;

class Role extends EntrustRole {}

Then we must add Permisson.php too to the models


use Zizaco\Entrust\EntrustPermission;

class Permission extends EntrustPermission {}

And now we must add HasRole trait to exiting User model


use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
use Zizaco\Entrust\HasRole;

class User extends Eloquent implements UserInterface, RemindableInterface {

	// This is trait for using entrust
	use HasRole;

	 * The database table used by the model.
	 * @var string
	protected $table = 'users';

And now we must dump composer using this code:

$ composer dump-autoload

Okay from above instruction is for installation Entrust, and now for usage entrust follow this instruction:


Example in this tutorial I just create two user, that is “Admin” and “User”. So for add this user to entrust table in MySQL, we must create code in the routes.php like this:


| Application Routes
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.

//form login
Route::get('/', array('before' => 'guest', function()
    return View::make('login');
Route::get('/start', function()
	$admin = new Role();
    $admin->name = 'Admin';
    $user = new Role();
    $user->name = 'User';
    $read = new Permission();
    $read->name = 'can_read';
    $read->display_name = 'Can Read Data';
    $edit = new Permission();
    $edit->name = 'can_edit';
    $edit->display_name = 'Can Edit Data';

	$adminRole = DB::table('roles')->where('name', '=', 'Admin')->pluck('id');
	$userRole = DB::table('roles')->where('name', '=', 'User')->pluck('id');
	// print_r($userRole);
	// die();
    $user1 = User::where('username','=','imron02')->first();
    $user2 = User::where('username','=','asih')->first();
    $user3 = User::where('username','=','sarah')->first();
    return 'Woohoo!';


  1. Line 20. That is example route, you can change with to route /hello or other.
  2. Line 22-28. This is to store new role to the database, or role table name in database, look at this picture:
  3. Line 30-38. This is use to create new permission, example from this tutorial I create new permission to only read, only edit, or can read and edit.
  4. Line 40-42. This is to assign a role to Admin or user, from that code I assign permission read and edit to admin, and only read to user.
  5. Line 44-45. This code is used to search an id from role table name in database. So I search id admin and save to variable $adminRole (value admin id is 1) and id for user is 2 and save to $userRole.
  6. Line 49-54. This code is used to add role to username, example from this tutorial user “imron02” is “Admin” and user “asih & sarah” is “User”.

And the question is:

How to use this permission?

Okay for the answer, open your validate login controller. Example I validate user login in HomeController.php:


class HomeController extends \BaseController {

	 * Display a listing of the resource.
	 * @return Response
	public function index()
		// attempt to do the login
        $auth = Auth::attempt(
                'username'  => strtolower(Input::get('username')),
                'password'  => Input::get('password')    
        if ($auth) {
            return Redirect::to('home');
        } else {
            // validation not successful, send back to form 
            return Redirect::to('/')
                ->with('flash_notice', 'Your username/password combination was incorrect.');

So from that controller if username and password match in the database, so redirect to /home route. And now change /home route to be like this:


| Application Routes
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.

//form login
Route::get('/', array('before' => 'guest', function()
    return View::make('login');

// check login
Route::post('login', 'HomeController@index');
// home page
Route::get('home', array('before' => 'auth', function()
    if(Entrust::hasRole('User')) {
            return View::make('home_user');
        else if(Entrust::hasRole('Admin')) {
            return View::make('home_admin');
        else {
            return Redirect::to('/login')
                ->with('flash_notice', 'You don\'t have access!');

    return App::abort(403);


  1. Line 26-36. This code is used for validate using entrust package. What different validate on HomeController with this?

    In the HomeController is to validate username and password and not validate the role and permission. But in this code, this is use to validate user with the role and permission.

Okay from above code we just explain how to validate user using role, but how to use using permission?
Example code if we want use permission validate, first open your filters.php and example we only validate for user with permission can_edit only can access URL with prefix /admin, so the code look like this:

Route::filter('can_edit', function()
    if (! Entrust::can('can_edit') ) // Checks the current user
        return Redirect::to('/home')->with('flash', 'You don\'t have access!');;

And for the route, you can use prefix for help with this validate, like this:

Route::when('admin/*', 'can_edit');
Route::group(array('prefix' => 'admin'), function()
	Route::get('major', 'AdminController@show');
	Route::post('major', 'AdminController@insert');

Explanations: So example if we open URL like this http://localhost/laravel/public/admin/major, so entrust will check the role permission, if the user does not have access to read then the code will be redirect to route /home with flash notice “You don’t have access!”.
For more info, you can read on this:


Source code: Download in here


  1. Great post. I was checking continuously this weblog and I’m impressed! Extremely useful information particularly the remaining part🙂 I care for such info much. I used to be seeking this certain information for a very lengthy time. Thank you and good luck.

  2. Pingback: Blogging
  3. Magnificent items from you, man. I have be mindful your
    stuff previous to and you’re just too fantastic. I actually like what you have acquired here, certainly like what
    you’re saying and the way by which you assert it.

    You are making it enjoyable and you still take care of to stay it wise.
    I cant wait to learn far more from you. That is actually a terrific

  4. You really make it seem so easy with your presentation but I find this
    matter to be actually something which I think I would never understand.
    It seems too complicated and extremely broad for me.
    I am looking forward for your next post, I’ll try to get
    the hang of it!

  5. Hi my loved one! I wish to say that this article is awesome, nice written and
    come with approximately all important infos. I’d like to see more posts like this .

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s