0% found this document useful (0 votes)
678 views13 pages

Create Role and Permission (Using Entrust) in Laravel - Imron02

This document provides instructions for adding role-based permissions to a Laravel application using the Entrust package. It explains how to install and configure Entrust, create roles and permissions, assign users to roles, and check permissions on routes. Key steps include generating an Entrust migration, assigning the HasRole trait to the User model, creating roles and permissions in routes, and using Entrust's authorization methods to control access. The document also demonstrates how to restrict routes to users with specific permissions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
678 views13 pages

Create Role and Permission (Using Entrust) in Laravel - Imron02

This document provides instructions for adding role-based permissions to a Laravel application using the Entrust package. It explains how to install and configure Entrust, create roles and permissions, assign users to roles, and check permissions on routes. Key steps include generating an Entrust migration, assigning the HasRole trait to the User model, creating roles and permissions in routes, and using Entrust's authorization methods to control access. The document also demonstrates how to restrict routes to users with specific permissions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

imron02

FromBeginnerToExpert

Createroleandpermission(UsingEntrust)
inLaravel
Longtimenotwriteblogagain,andnowIwantsharehowtoaddpermissionuserusingentrust
(https://github.com/Zizaco/entrust).Okayfortheinstallation,followthestepsbelow:
Firstopenyourlaravelprojectandaddthiscodetoyourcomposer:
6
7
8
9
10

"require":{
"laravel/framework":"4.*",
"barryvdh/laraveldebugbar":"devmaster",
"zizaco/entrust":"devmaster"
},

Afterthat,runcomposerupdate:
1

$composerupdate

Ifupdatesuccesfully,nowopenyourapp.phpfromyourlaravelconfig:
app/config/app.php
90
91
92
93
94
95
96

'providers'=>array(

'Illuminate\Foundation\Providers\ArtisanServiceProvider',
'Illuminate\Auth\AuthServiceProvider',
.....
'Zizaco\Entrust\EntrustServiceProvider',
),

Anddontforgettoaddaliases:
app/config/app.php
146
147
148

'aliases'=>array(

'App'=>'Illuminate\Support\Facades\App',

148
149

'App'=>'Illuminate\Support\Facades\App',
'Artisan'=>'Illuminate\Support\Facades\Artisan',

150
151
152

.............
'Entrust'=>'Zizaco\Entrust\EntrustFacade',
),

Andbeforetothenextstep,Iassumeyourlaravelalreadyhavedatabaseconnected.Thisis
examplemyconfig:
app/config/database.php
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

'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'=>'',
),

Andthisisdatafrommyuserstable:

ThennowwemustgeneratetheEntrustmigration(createfilemigrationforentrust):
1

$phpartisanentrust:migration

Andthewemustmigratethatfile:
1

$phpartisanmigrate

Ifright,yourdatabasehavesomenewtablelikethis:

AndnowexampleIusesourcefromlatesttutorialfromhere
https://imron02.wordpress.com/2013/12/21/simple-login-using-laravel-4/
(https://imron02.wordpress.com/2013/12/21/simple-login-using-laravel-4/)andIjustchange
litlesourceandaddcodeforusingroleandpermissioninthistutorial.
OkaynextwemustaddRole.phptothemodels.
app/models/Role.php
1
2
3
4
5

<?php

useZizaco\Entrust\EntrustRole;

classRoleextendsEntrustRole{}

ThenwemustaddPermisson.phptootothemodels
app/models/Permission.php
1
2
3
4
5

<?php

useZizaco\Entrust\EntrustPermission;

classPermissionextendsEntrustPermission{}

AndnowwemustaddHasRoletraittoexitingUsermodel
app/models/User.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

<?php

useIlluminate\Auth\UserInterface;
useIlluminate\Auth\Reminders\RemindableInterface;
useZizaco\Entrust\HasRole;

classUserextendsEloquentimplementsUserInterface,RemindableInterface{

//Thisistraitforusingentrust
useHasRole;

/**
*Thedatabasetableusedbythemodel.
*
*@varstring
*/
protected$table='users';

Andnowwemustdumpcomposerusingthiscode:
1

$composerdumpautoload

OkayfromaboveinstructionisforinstallationEntrust,andnowforusageentrustfollowthis

instruction:

Usage
ExampleinthistutorialIjustcreatetwouser,thatisAdminandUser.Soforaddthisuserto
entrusttableinMySQL,wemustcreatecodeintheroutes.phplikethis:
app/routes.php
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
37
38
39
40

<?php

/*
|
|ApplicationRoutes
|
|
|Hereiswhereyoucanregisteralloftheroutesforanapplication.
|It'sabreeze.SimplytellLaraveltheURIsitshouldrespondto
|andgiveittheClosuretoexecutewhenthatURIisrequested.
|
*/

//formlogin
Route::get('/',array('before'=>'guest',function()
{
returnView::make('login');
}));
..........
Route::get('/start',function()
{
$admin=newRole();
$admin>name='Admin';
$admin>save();

$user=newRole();
$user>name='User';
$user>save();

$read=newPermission();
$read>name='can_read';
$read>display_name='CanReadData';
$read>save();

$edit=newPermission();
$edit>name='can_edit';
$edit>display_name='CanEditData';
$edit>save();

$user>attachPermission($read);

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

$admin>attachPermission($read);
$admin>attachPermission($edit);

$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();
$user1>roles()>attach($adminRole);
$user2=User::where('username','=','asih')>first();
$user2>roles()>attach($userRole);
$user3=User::where('username','=','sarah')>first();
$user3>roles()>attach($userRole);
return'Woohoo!';
});

Explanations:
1. Line20.Thatisexampleroute,youcanchangewithtoroute/helloorother.
2. Line22-28.Thisistostorenewroletothedatabase,orroletablenameindatabase,lookatthis
picture:

3. Line30-38.Thisisusetocreatenewpermission,examplefromthistutorialIcreatenew
permissiontoonlyread,onlyedit,orcanreadandedit.

4. Line40-42.ThisistoassignaroletoAdminoruser,fromthatcodeIassignpermissionread
andedittoadmin,andonlyreadtouser.

5. Line44-45.Thiscodeisusedtosearchanidfromroletablenameindatabase.SoIsearchid
adminandsavetovariable$adminRole(valueadminidis1)andidforuseris2andsaveto
$userRole.
6. Line49-54.Thiscodeisusedtoaddroletousername,examplefromthistutorialuser
imron02isAdminanduserasih&sarahisUser.

Andthequestionis:

Howtousethispermission?
Okayfortheanswer,openyourvalidatelogincontroller.ExampleIvalidateuserloginin
HomeController.php:
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

<?php

classHomeControllerextends\BaseController{

/**
*Displayalistingoftheresource.
*
*@returnResponse
*/
publicfunctionindex()
{
//attempttodothelogin
$auth=Auth::attempt(
[
'username'=>strtolower(Input::get('username')),
'password'=>Input::get('password')
]
);
if($auth){
returnRedirect::to('home');
}else{
//validationnotsuccessful,sendbacktoform
returnRedirect::to('/')
>withInput(Input::except('password'))
>with('flash_notice','Yourusername/passwordcombinationwa
}
}
}

Sofromthatcontrollerifusernameandpasswordmatchinthedatabase,soredirectto/home
route.Andnowchange/homeroutetobelikethis:
app/routes.php
1
2
3
4
5
6
7
8
9
10
11
12
13

<?php

/*
|
|ApplicationRoutes
|
|
|Hereiswhereyoucanregisteralloftheroutesforanapplication.
|It'sabreeze.SimplytellLaraveltheURIsitshouldrespondto
|andgiveittheClosuretoexecutewhenthatURIisrequested.
|
*/

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

//formlogin
Route::get('/',array('before'=>'guest',function()
{
returnView::make('login');
}));

//checklogin
Route::post('login','HomeController@index');

//homepage
Route::get('home',array('before'=>'auth',function()
{
if(Entrust::hasRole('User')){
returnView::make('home_user');
}
elseif(Entrust::hasRole('Admin')){
returnView::make('home_admin');
}
else{
Auth::logout();
returnRedirect::to('/login')
>with('flash_notice','Youdon\'thaveaccess!');
}

returnApp::abort(403);
}));

Explanations:
1. Line26-36.Thiscodeisusedforvalidateusingentrustpackage.Whatdifferentvalidateon
HomeControllerwiththis?
IntheHomeControlleristovalidateusernameandpasswordandnotvalidatetheroleand
permission.Butinthiscode,thisisusetovalidateuserwiththeroleandpermission.
Okayfromabovecodewejustexplainhowtovalidateuserusingrole,buthowtouseusing
permission?
Examplecodeifwewantusepermissionvalidate,firstopenyourfilters.phpandexamplewe
onlyvalidateforuserwithpermissioncan_editonlycanaccessURLwithprefix/admin,sothe
codelooklikethis:
app/filters.php
1
2
3
4
5
6
7

Route::filter('can_edit',function()
{
if(!Entrust::can('can_edit'))//Checksthecurrentuser
{
returnRedirect::to('/home')>with('flash','Youdon\'thaveaccess!'
}
});

Andfortheroute,youcanuseprefixforhelpwiththisvalidate,likethis:
app/routes.php
1
2
3
4
5
6

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

Explanations:SoexampleifweopenURLlikethis
http://localhost/laravel/public/admin/major
(http://localhost/laravel/public/admin/major),soentrustwillchecktherolepermission,
iftheuserdoesnothaveaccesstoreadthenthecodewillberedirecttoroute/homewithflash
noticeYoudonthaveaccess!.
Formoreinfo,youcanreadonthis:
1. https://github.com/Zizaco/entrust(https://github.com/Zizaco/entrust)
2. http://alexsears.com/article/using-entrust-to-add-roles-and-permissions-to-laravel-4
(http://alexsears.com/article/using-entrust-to-add-roles-and-permissions-to-laravel-4)
Sourcecode:Downloadinhere
(http://www.mediafire.com/download/seydp5n3gnzob72/laravel_entrust.7z)
About these ads (https://wordpress.com/about-these-ads/)

YouMayLike

1.
Twenty
FiveAmazingPerfectlyTimed
Photos3weeksagozonable.com
Zonable.comZonable.com
(sponsored)
PostedinFramework,Laravelandtaggedentrust,Laravel,Laravel4,phponJuly23,2014by
imron02.19Comments

19comments
1. GafasOakleyFrogskinsBaratassays:

August5,2014at8:29am
Greatpost.IwascheckingcontinuouslythisweblogandImimpressed!Extremelyuseful
informationparticularlytheremainingpart Icareforsuchinfomuch.Iusedtobeseeking
thiscertaininformationforaverylengthytime.Thankyouandgoodluck.
REPLY
2. Pingback:Blogging
1. imron02says:
August21,2014at11:46am
Ijustusingwordpress
REPLY
3. comprarslipsCalvinKleinsays:
August13,2014at8:43am
Itsactuallyacoolandhelpfulpieceofinfo.Iamhappythatyoujustsharedthishelpful
informationwithus.Pleasekeepusinformedlikethis.Thankyouforsharing.
REPLY
4. IntelPcsays:
August21,2014at9:42am
justwhatIwaslookingfor,thanks
REPLY
5. Vanessasays:
October22,2014at7:57pm
Magnificentsite.Lotsofhelpfulinformationhere.
Iamsendingittoseveralpalsansalsosharing
indelicious.Andcertainly,thankyouinyoursweat!
REPLY
6. WahyuTAUFIKsays:
November17,2014at1:05pm
itworksbro
REPLY
1. imron02says:
November21,2014at10:48am
Hahayoidong..
REPLY
7. VinodSPattarsays:
December1,2014at1:06pm
Iwaslookingforhowtoattachroleforuser!Justfoundit
REPLY

Thankyou!

8. BrustvergrerungPreissays:
December8,2014at5:25pm
Thisisreallyinteresting,Youreaveryskilledblogger.
Ivejoinedyourfeedandlookforwardtoseekingmoreofyourexcellentpost.
Also,Ivesharedyourwebsiteinmysocialnetworks!
REPLY
9. Lavonnesays:
December25,2014at12:03am
Magnificentitemsfromyou,man.Ihavebemindfulyour
stuffprevioustoandyourejusttoofantastic.Iactuallylikewhatyouhaveacquiredhere,
certainlylikewhat
youresayingandthewaybywhichyouassertit.
Youaremakingitenjoyableandyoustilltakecareoftostayitwise.
Icantwaittolearnfarmorefromyou.Thatisactuallyaterrific
website.
REPLY
10. nbasays:
December25,2014at3:35pm
NiceBlog,thanksforsharingthiskindofinformation.
REPLY
11. says:
January5,2015at5:53am
NiceBlog,thanksforsharingthiskindofinformation.
REPLY
12. chatosays:
January10,2015at10:03am
Icanuseentrustonlyforroles?
REPLY
13. AndhikaMahevaWicaksonosays:
February3,2015at1:44am
GreatBlog.Finallyifoundyourarticleformyproblem.Thankyousomuch!
REPLY
14. constructionmanagementsoftwaresays:
February25,2015at10:05pm
Formostrecentnewsyouhavetovisitthewebandonworld-wide-webI
foundthiswebsiteasabestwebsiteformostrecentupdates.

REPLY
15. jualaksesoriscincinkoreasays:
May11,2015at8:36am
Hello!WouldyoumindifIshareyourblogwithmyzyngagroup?
TheresalotoffolksthatIthinkwouldreallyappreciateyourcontent.
Pleaseletmeknow.Cheers
REPLY
1. imron02says:
May18,2015at5:53pm
Yesyoucanshareit..
REPLY
16. aksesoriskalungonlineshopsays:
May15,2015at8:14pm
YoureallymakeitseemsoeasywithyourpresentationbutIfindthis
mattertobeactuallysomethingwhichIthinkIwouldneverunderstand.
Itseemstoocomplicatedandextremelybroadforme.
Iamlookingforwardforyournextpost,Illtrytoget
thehangofit!
REPLY

BLOGATWORDPRESS.COM.THESUITSTHEME.
Follow

Followimron02
BuildawebsitewithWordPress.com

You might also like