Laravel5.1 storing control permissions to a database

Source: Internet
Author: User

The previous article recorded how to use policy, generally to do a complete Web site we need to have a series of administrative rights stored in the database, so that we can more flexible use of user control permissions, first we create two model permission (permissions) and role (roles):

Logical relationship

We created the permissions and the role model, and now we have to generate the corresponding data table, but first to understand the relationship between them, a permission can be used by many users, a user can have a lot of permissions, it is obvious that this is a many-to-many relationship, then we need to create a third relational table in the migration file.

For convenience I created 3 tables in a migration:

PHP Artisan make:migration create_permission_role_table--create=roles
     Public functionUp () {//Create a role tableSchema::create (' Roles ',function(Blueprint$table) {            $table->increments (' id '); $table-string(' name ');//names of characters, such as admin and number            $table-string(' lable ')->nullable ();//role Label (nullable)            $table-timestamps ();        }); //Create permission TableSchema::create (' Permissions ',function(Blueprint$table) {            $table->increments (' id '); $table-string(' name ');//names of permissions, such as update and delete            $table-string(' lable ')->nullable ();//Label for permissions (nullable)            $table-timestamps ();        }); //create a many-to-many association tableSchema::create (' Permission_role ',function(Blueprint$table) {            $table-integer(' permission_id ')unsigned (); $table-integer(' role_id ')unsigned (); //declaring permisstion_id foreign keys            $table->foreign (' permission_id ')                  ->references (' id ')                  ->on (' Permissions ')                  ->ondelete (' Cascade '); //declaring role_id foreign keys            $table->foreign (' role_id ')                  ->references (' id ')                  ->on (' Roles ')                  ->ondelete (' Cascade '); //Set Primary Key            $table->primary ([' permission_id ', ' role_id ']);    }); }

So our many-to-many relationship is set up, but not enough, we need to add a relationship to the user table and the roles table, so we're adding a table

        //Create an association table for user and roleSchema::create (' User_role ',function(Blueprint$table) {            $table-integer(' user_id ')unsigned (); $table-integer(' role_id ')unsigned (); //declaring user_id foreign keys            $table->foreign (' user_id ')                ->references (' id ')                ->on (' Users ')                ->ondelete (' Cascade '); //declaring role_id foreign keys            $table->foreign (' role_id ')                ->references (' id ')                ->on (' Roles ')                ->ondelete (' Cascade '); //Set Primary Key            $table->primary ([' user_id ', ' role_id ']); });

Now we can build the table:

Declaring a many-to-many relationship in a model

Having just implemented a many-to-many relationship in the table, we now create many-to-many relationships in the model, first of all the permission models:

Permission model
class extends model{    publicfunction  roles ()    {        //  Here you use Belongstomany instead of Belongsto because they are a many-to-many relationship        return$this->belongstomany (Role:: class );    }}
Role model
class extends model{    publicfunction  permissions ()    {        return$this ->belongstomany (Permission::class);    }}

In role we are declaring a method:

    // Give permission     Public function $permission )    {        $this->permissions ()->save ($permission);    }
User model
     Public function roles ()    {        return$this->belongstomany (Role::class);    }

Generate Data

We generate data in tinker and write after entering Tinker:

 >>> namespace App;  = = null  >>>  $role  = new   Role ();  = = App\role {#  665}  >>>  $role ->name = ' admin ' ;  = "Admin" >>>  $role ->lable = ' admin '  = "Admin" >>>  $role ->save ();  = = true  
$permission New Permission; = = app\permission {#669}$permission->name = ' edit_form '; $permission->lable = ' Edit the Form '; Save ($permission); true

The above has already added two data in the database, but it is not added in the associated table, but we have declared the Givepermission method, we add it directly in the tinker:

$role->givepermission ($permission);

Looking at our database, we have now added an association relationship.

Start testing

We're going to add control right now, open authserviceprovider, and go to the boot method and add the following code:

     Public functionBoot (gatecontract$gate)    {        $this->registerpolicies ($gate); //Loop out Permissions        foreach(Permission::with (' Roles ')->get () as $permission){            $gate-Define($permission->name,function(User$user) Use($permission){                return $user->hasrole ($permission-roles);        }); }    }

Declare the Hasrole method in User:

     Public function hasrole ($role)    {        if (is_string($role  ) {            //  does this string exist (name)            return$this->roles-> Contains ($role);        }         return $role->intersect ($this->roles),Count();    }

It's just that our user_role table doesn't have data yet. We created it under Tinker:

>>>$role= App\role::First ();= = App\role {#659Id:1,name: "Admin",lable: "Admin",Created_at: "2017-03-25 04:54:55",Updated_at: "2017-03-25 04:54:55",   }>>>$user= App\user::First ();= = App\user {#661Id:1,name: "Dorcas Johnston",Email: "[email protected]",Created_at: "2017-03-25 04:53:00",Updated_at: "2017-03-25 04:53:00",   }>>>$user->roles ()->save ($role);= = App\role {#659Id:1,name: "Admin",lable: "Admin",Created_at: "2017-03-25 04:54:55",Updated_at: "2017-03-25 04:54:55",   }

We return to view to see the results:

     Public function index ()    {        \auth:: Loginusingid (2);         $post = post::findorfail (1);         return Compact (' Post '));    }

The code for show.blade.php is as follows:

<!DOCTYPE HTML><HTML><Head>    <MetaCharSet= "UTF-8"></Head><Body>    <H1>{{$post->title}}</H1>@can (' Edit_form ')<ahref="#">Edit</a>@endcan</Body></HTML>

We landed the user ID 2, the user does not have the admin role so the edit link will not be displayed, but our login ID of 1 users will show the edit link.

Laravel5.1 storing control permissions to a database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.