Upload
yrvin-escorihuela
View
55
Download
0
Embed Size (px)
DESCRIPTION
Create Role and Permission (Using Entrust) in Laravel _ Imron02
Citation preview
imron02
From Beginner To Expert
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(https://github.com/Zizaco/entrust). Okay for the installation, follow the steps below:First open your laravel project and add this code to your composer:
After that, run composer update:
If update succesfully, now open your app.php from your laravel config:
And don’t forget to add aliases:
678910
"require": { "laravel/framework": "4.*", "barryvdh/laravel‐debugbar": "dev‐master", "zizaco/entrust": "dev‐master" },
1 $ composer update
app/config/app.php90919293949596
'providers' => array( 'Illuminate\Foundation\Providers\ArtisanServiceProvider', 'Illuminate\Auth\AuthServiceProvider', ..... 'Zizaco\Entrust\EntrustServiceProvider',),
app/config/app.php146147148
'aliases' => array( 'App' => 'Illuminate\Support\Facades\App',
And before to the next step, I assume your laravel already have database connected. This isexample my config:
And this is data from my users table:
148149
150151152
'App' => 'Illuminate\Support\Facades\App', 'Artisan' => 'Illuminate\Support\Facades\Artisan',
............. 'Entrust' => 'Zizaco\Entrust\EntrustFacade',),
app/config/database.php4748495051525354555657585960616263646566676869
'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' => '', ),
Then now we must generate the Entrust migration (create file migration for entrust):
And the we must migrate that file:
If right, your database have some new table like this:
1 $ php artisan entrust:migration
1 $ php artisan migrate
And now example I use source from latest tutorial from herehttps://imron02.wordpress.com/2013/12/21/simple-login-using-laravel-4/(https://imron02.wordpress.com/2013/12/21/simple-login-using-laravel-4/) and I just changelitle source and add code for using role and permission in this tutorial.Okay next we must add Role.php to the models.
Then we must add Permisson.php too to the models
And now we must add HasRole trait to exiting User model
And now we must dump composer using this code:
Okay from above instruction is for installation Entrust, and now for usage entrust follow this
app/models/Role.php12345
<?php use Zizaco\Entrust\EntrustRole; class Role extends EntrustRole {}
app/models/Permission.php12345
<?php use Zizaco\Entrust\EntrustPermission; class Permission extends EntrustPermission {}
app/models/User.php1234567891011121314151617
<?php 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';
1 $ composer dump‐autoload
instruction:
Usage
Example in this tutorial I just create two user, that is “Admin” and “User”. So for add this user toentrust table in MySQL, we must create code in the routes.php like this:
app/routes.php12345678910111213141516171819202122232425262728293031323334353637383940
<?php /*|‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐| 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 loginRoute::get('/', array('before' => 'guest', function(){ return View::make('login');}));..........Route::get('/start', function(){ $admin = new Role(); $admin‐>name = 'Admin'; $admin‐>save(); $user = new Role(); $user‐>name = 'User'; $user‐>save(); $read = new Permission(); $read‐>name = 'can_read'; $read‐>display_name = 'Can Read Data'; $read‐>save(); $edit = new Permission(); $edit‐>name = 'can_edit'; $edit‐>display_name = 'Can Edit Data'; $edit‐>save(); $user‐>attachPermission($read);
Explanations:
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 newpermission to only read, only edit, or can read and edit.
41424344454647484950515253545556
$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!';});
4. Line 40-42. This is to assign a role to Admin or user, from that code I assign permission readand 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 idadmin 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 inHomeController.php:
So from that controller if username and password match in the database, so redirect to /homeroute. And now change /home route to be like this:
12345678910111213141516171819202122232425262728
<?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('/') ‐>withInput(Input::except('password')) ‐>with('flash_notice', 'Your username/password combination was incorrect.' } }}
app/routes.php12345678910111213
<?php /*|‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐| 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.|*/
Explanations:
1. Line 26-36. This code is used for validate using entrust package. What different validate onHomeController with this?
In the HomeController is to validate username and password and not validate the role andpermission. 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 usingpermission?Example code if we want use permission validate, first open your filters.php and example weonly validate for user with permission can_edit only can access URL with prefix /admin, so thecode look like this:
1415161718192021222324252627282930313233343536373839
//form loginRoute::get('/', array('before' => 'guest', function(){ return View::make('login');})); // check loginRoute::post('login', 'HomeController@index'); // home pageRoute::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 { Auth::logout(); return Redirect::to('/login') ‐>with('flash_notice', 'You don\'t have access!'); } return App::abort(403);}));
app/filters.php1234567
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:
Explanations: So example if we open URL like thishttp://localhost/laravel/public/admin/major(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 flashnotice “You don’t have access!”.For more info, you can read on this:
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)
Source code: Download in here(http://www.mediafire.com/download/seydp5n3gnzob72/laravel_entrust.7z)
Posted in Framework, Laravel and tagged entrust, Laravel, Laravel4, php on July 23, 2014 byimron02. 19 Comments
19 comments
1. Gafas Oakley Frogskins Baratas says:
app/routes.php123456
Route::when('admin/*', 'can_edit');Route::group(array('prefix' => 'admin'), function(){ Route::get('major', 'AdminController@show'); Route::post('major', 'AdminController@insert');});
You May Like
1. TwentyFive Amazing Perfectly TimedPhotos 3 weeks ago zonable.comZonable.com Zonable.com(sponsored)
About these ads (https://wordpress.com/about-these-ads/)
August 5, 2014 at 8:29 amGreat post. I was checking continuously this weblog and I’m impressed! Extremely usefulinformation particularly the remaining part I care for such info much. I used to be seekingthis certain information for a very lengthy time. Thank you and good luck.
REPLY2. Pingback: Blogging
1. imron02 says:August 21, 2014 at 11:46 am
I just using wordpress
REPLY3. comprar slips Calvin Klein says:
August 13, 2014 at 8:43 amIt’s actually a cool and helpful piece of info. I am happy that you just shared this helpfulinformation with us. Please keep us informed like this. Thank you for sharing.
REPLY4. Intel Pc says:
August 21, 2014 at 9:42 amjust what I was looking for, thanks …
REPLY5. Vanessa says:
October 22, 2014 at 7:57 pmMagnificent site. Lots of helpful information here.I am sending it to several pals ans also sharingin delicious. And certainly, thank you in your sweat!
REPLY6. Wahyu TAUFIK says:
November 17, 2014 at 1:05 pmit works bro
REPLY1. imron02 says:
November 21, 2014 at 10:48 am
Haha yoi dong..
REPLY7. Vinod S Pattar says:
December 1, 2014 at 1:06 pm
I was looking for how to attach role for user! Just found it Thank you!
REPLY
8. Brustvergrößerung Preis says:December 8, 2014 at 5:25 pmThis is really interesting, You’re a very skilled blogger.
I’ve joined your feed and look forward to seeking more of your excellent post.
Also, I’ve shared your web site in my social networks!
REPLY9. Lavonne says:
December 25, 2014 at 12:03 amMagnificent items from you, man. I have be mindful yourstuff previous to and you’re just too fantastic. I actually like what you have acquired here,certainly like whatyou’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 terrificwebsite.
REPLY10. nba即時比分 says:
December 25, 2014 at 3:35 pmNice Blog, thanks for sharing this kind of information.
REPLY11. 九州娛樂城 says:
January 5, 2015 at 5:53 amNice Blog, thanks for sharing this kind of information.
REPLY12. chato says:
January 10, 2015 at 10:03 amI can use entrust only for roles?
REPLY13. Andhika Maheva Wicaksono says:
February 3, 2015 at 1:44 am
Great Blog. Finally i found your article for my problem. Thank you so much !
REPLY14. construction management software says:
February 25, 2015 at 10:05 pmFor most recent news you have to visit the web and on world-wide-web Ifound this website as a best web site for most recent updates.
REPLY15. jual aksesoris cincin korea says:
May 11, 2015 at 8:36 amHello! Would you mind if I share your blog with my zynga group?There’s a lot of folks that I think would really appreciate your content.Please let me know. Cheers
REPLY1. imron02 says:
May 18, 2015 at 5:53 pm
Yes you can share it..
REPLY16. aksesoris kalung online shop says:
May 15, 2015 at 8:14 pmYou really make it seem so easy with your presentation but I find thismatter 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 getthe hang of it!
REPLY
BLOG AT WORDPRESS.COM. THE SUITS THEME.
Follow
Follow “imron02”
Build a website with WordPress.com