Coder Social home page Coder Social logo

laravel-permission's Introduction

Laravel permission

An easy and flexible Laravel authorization and roles permission management

Why we need a Laravel permission package

In many projects, we need to implement a role-based permissions management system for our users. Although Laravel has the best tools to manage users' permissions, I build this package to make it simpler, more flexible, and to avoid duplicate work in many web projects built on Laravel.

How to use

The idea is to use this package as easy and as flexible as possible.
This package creates a list of all your routes and assigns these permissions list to user roles.
Although the laravel-permission package does most of the work, you could easily extend it and implement your authorization system.

Installation

Start with installing the package through the composer. Run this command in your terminal:

$ composer require amir/laravel-permission

After that, you need to run the migration files:

$ php artisan migrate

How to authorize user

This package adds a role_id to the users table. Roles are stored in the roles table. You can assign a role to a user in your administrator panel or by creating a seed file.
Then, you only need to assign auth.role middleware to your routes.

Assign a route to a role

Besides middleware and other route settings, you can use a role key in your route groups to assign a role to your routes.
You can put your routes for a role in a Route group like this:

Route::group([
    'middleware' => 'auth.role',
    'prefix' => ...,
    'role' => ['admin', 'customer'],
    ...
],function (){
    ...
    Route::get('/home', 'HomeController@index')->name('home');
    Route::get('/product', 'ProductController@index');
    ...
});

Of course, you can have as many as route groups like this.
Then you need to run this artisan command to register all permissions:

$ php artisan permissions:generate 

This command will register all permissions and assign permissions to the roles.
If you add a fresh option to this command, it will delete all data and generate fresh permissions data:

$ php artisan permissions:generate --fresh

Now only users with the proper role can access the route assigned to them.
Don't forget that this package does not handle assigning roles to the users. You need to handle this in your administration panel or anywhere else you handle your users.
Again, if you want to add permissions to the routes manually it is not necessary to add `role` key in your route group. You can easily assign permissions to the roles in your administration panel or create another seed file for that.

How to create roles

The php artisan permissions:generate command will make all roles defined in the routes if they are not exist.
Also, You can create a seeder to fill the roles table. It takes only a name field.
Your RolesSeeser file can look like this.

Role::firstOrCreate(['name' => 'admin']);
Role::firstOrCreate(['name' => 'customer']);

Don't forget to import the Role model in your seeder.

use Amir\Permission\Models\Role;

How to clear permissions

To clear registered permissions you can run this command:

$ php artisan permissions:clear

You can use this command to clear all permissions data for a specific role

$ php artisan permissions:clear --roles role1 role2

To erase only permissions list, run permissions:clear command with this option:

$ php artisan permissions:clear --tables permissions

To clear all roles:

$ php artisan permissions:clear --tables roles

To clear only permissions role relation:

$ php artisan permissions:clear --tables permission_role

This command erases all permissions assigned to roles, so you can regenerate permissions

Also, you can use these options in combination:

$ php artisan permissions:clear --roles admin --tables permission_role

About

I used this Laravel permission management method in my projects for a while. It made manging Laravel permission easy and flexible for me. I hope it helps you as well. All pull requests are welcome.
Most of the work is based on my article about Laravel authorization and roles permission management

laravel-permission's People

Contributors

a-yousefi avatar aahelali avatar amiryousefi avatar asia-coder avatar hackerinos2 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

laravel-permission's Issues

Assign more then 1 role to a route

How can I assign more then one role to a route? I tried this, but its not working:

Route::group([
    'middleware' => 'auth.role',
    'role' => ['moderator', 'admin'],
]

id on roles table does not exist.

When migrating, this error comes up:
BadMethodCallException : Method Illuminate\Database\Schema\Blueprint::id does not exist.

this is because id on the roles schema has been set as a datatype instead of increments

For example: $table->increments('id');

Error when try use php artisan permissions:generate --fresh

Illuminate\Database\QueryException

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (esi.users, CONSTRAINT users_role_id_foreign FOREIGN KEY (role_id) REFERENCES roles (id)) (SQL: delete from roles)

at C:\laragon\www\esi\vendor\laravel\framework\src\Illuminate\Database\Connection.php:671

    667|         // If an exception occurs when attempting to run a query, we'll format the error
    668|         // message to include the bindings with SQL, which will make this exception a
    669|         // lot more helpful to the developer instead of just the database's errors.
    670|         catch (Exception $e) {
  > 671|             throw new QueryException(
    672|                 $query, $this->prepareBindings($bindings), $e
    673|             );
    674|         }
    675| 

1 C:\laragon\www\esi\vendor\laravel\framework\src\Illuminate\Database\Connection.php:489
PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (esi.users, CONSTRAINT users_role_id_foreign FOREIGN KEY (role_id) REFERENCES roles (id))")

2 C:\laragon\www\esi\vendor\laravel\framework\src\Illuminate\Database\Connection.php:489
PDOStatement::execute()

Help with installation

Hey, I really like the Plugin and would like to use it, but I'm having some problems with installation.
For installation I made all the following steps, but when I navigate to my assigned route with role admin, I get redirected to my 404 page.

I installed via composer and run php artisan migrate. Then I created a Seeder:

<?php

use Illuminate\Database\Seeder;
use Amir\Permission\Models\Role;

class RolesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
       	        Role::firstOrCreate(['name' => 'admin']);
		Role::firstOrCreate(['name' => 'moderator']);
		Role::firstOrCreate(['name' => 'jakob']);
		Role::firstOrCreate(['name' => 'user']);
    }
}

Then I run artisan db:seed --class=RolesTableSeeder.

Then I copied over your src/Middleware/AuthRoles.php to App\Http\Middleware\AuthRoles.php.
In App\ḨTTP\Kernel.php I registered the Middleware:

protected $routeMiddleware = [
        ...
        'auth.role' => \App\Http\Middleware\AuthRoles::class,
        ...
    ];

After I setup my routes routes\web.php:

Route::group([
    'middleware' => 'auth.role',
    'prefix' => 'test',
    'role' => 'admin',
],function (){
    Route::get('/test', 'MyTest@index');
});

And run php artisan permissions:generate.
Then I set my user profile table role_id in phpmyadmin to 1 (admin).

EDIT: After i registered the provider in config\app.php

'providers' => [
    ....
    Amir\Permission\LaravelPermissionServiceProvider::class,
    ....
],

All roles are in the db table, all permissions are in the db table and there is also the permission_role inserted in the database. Now when I goto my route /test I get redireted to 404 Page.
Can you help me?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.