Está en la página 1de 13

21/6/2015

Createroleandpermission(UsingEntrust)inLaravel|imron02

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

https://imron02.wordpress.com/2014/07/23/createroleandpermissionusingentrustinlaravel/

1/13

21/6/2015

Createroleandpermission(UsingEntrust)inLaravel|imron02

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:

https://imron02.wordpress.com/2014/07/23/createroleandpermissionusingentrustinlaravel/

2/13

21/6/2015

Createroleandpermission(UsingEntrust)inLaravel|imron02

ThennowwemustgeneratetheEntrustmigration(createfilemigrationforentrust):
1

$phpartisanentrust:migration

Andthewemustmigratethatfile:
1

$phpartisanmigrate

Ifright,yourdatabasehavesomenewtablelikethis:

https://imron02.wordpress.com/2014/07/23/createroleandpermissionusingentrustinlaravel/

3/13

21/6/2015

Createroleandpermission(UsingEntrust)inLaravel|imron02

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
https://imron02.wordpress.com/2014/07/23/createroleandpermissionusingentrustinlaravel/

4/13

21/6/2015

Createroleandpermission(UsingEntrust)inLaravel|imron02

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);

https://imron02.wordpress.com/2014/07/23/createroleandpermissionusingentrustinlaravel/

5/13

21/6/2015

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

Createroleandpermission(UsingEntrust)inLaravel|imron02

$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.

https://imron02.wordpress.com/2014/07/23/createroleandpermissionusingentrustinlaravel/

6/13

21/6/2015

Createroleandpermission(UsingEntrust)inLaravel|imron02

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:
https://imron02.wordpress.com/2014/07/23/createroleandpermissionusingentrustinlaravel/

7/13

21/6/2015

Createroleandpermission(UsingEntrust)inLaravel|imron02

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.
|
*/

https://imron02.wordpress.com/2014/07/23/createroleandpermissionusingentrustinlaravel/

8/13

21/6/2015

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

Createroleandpermission(UsingEntrust)inLaravel|imron02

//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!'
}
});

https://imron02.wordpress.com/2014/07/23/createroleandpermissionusingentrustinlaravel/

9/13

21/6/2015

Createroleandpermission(UsingEntrust)inLaravel|imron02

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 (http://wordpress.com/about-these-ads/)

YouMayLike
1.

PostedinFramework,Laravelandtaggedentrust,Laravel,Laravel4,phponJuly23,2014by
imron02.19Comments

19comments
1. GafasOakleyFrogskinsBaratassays:
August5,2014at8:29am
https://imron02.wordpress.com/2014/07/23/createroleandpermissionusingentrustinlaravel/

10/13

21/6/2015

Createroleandpermission(UsingEntrust)inLaravel|imron02

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

Thankyou!

REPLY
8. BrustvergrerungPreissays:
https://imron02.wordpress.com/2014/07/23/createroleandpermissionusingentrustinlaravel/

11/13

21/6/2015

Createroleandpermission(UsingEntrust)inLaravel|imron02

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:
https://imron02.wordpress.com/2014/07/23/createroleandpermissionusingentrustinlaravel/

12/13

21/6/2015

Createroleandpermission(UsingEntrust)inLaravel|imron02

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

CREATEAFREEWEBSITEORBLOGATWORDPRESS.COM.THESUITSTHEME.
Follow

Followimron02
BuildawebsitewithWordPress.com

https://imron02.wordpress.com/2014/07/23/createroleandpermissionusingentrustinlaravel/

13/13

También podría gustarte