Giter VIP home page Giter VIP logo

laravel-roles's Introduction

Laravel Roles

Latest Version on Packagist Test Total Downloads

A simple, flexible roles implementation for Laravel v10.

See v2.3 for Laravel 6-9 support.

Installation

Install with composer

$ composer require codinglabsau/laravel-roles

Publish migrations and migrate

php artisan vendor:publish --tag="roles-migrations"
php artisan migrate

Configuration

If you need to override the default Role model, you can do that by publishing the config and setting the models.role option.

php artisan vendor:publish --tag="roles-config"

Usage

Add the trait

Add the HasRoles trait to your user model:

use Codinglabs\Roles\HasRoles;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable, HasRoles;
}

Create roles

$role = \Codinglabs\Roles\Role::create(['name' => 'manager']);

Get roles

$managerRole = \Codinglabs\Roles\Role::whereName('manager')->first();

Associate roles

Under the hood we are using Eloquent many-to-many relationships.

use Codinglabs\Roles\Role;

// attach multiple roles
$user->roles()->attach([
    Role::whereName('employee')->first()->id,
    Role::whereName('manager')->first()->id,
]);

// detach a single role
$user->roles()->detach(Role::whereName('employee')->first());

// update roles to match array
$user->roles()->sync([
    Role::whereName('employee')->first()->id,
]);

// ensure roles in array are attached without detaching others
$user->roles()->syncWithoutDetaching([
    Role::whereName('employee')->first()->id,
]);

Protect routes with middleware

In App\Http\Kernel, register the middeware:

protected $routeMiddleware = [
    // ...
    'role' => \Codinglabs\Roles\CheckRole::class,
];

And then call the middleware in your routes, seperating multiple roles with a pipe:

Route::middleware('role:employee')->...
Route::middleware('role:manager|admin')->...

Or with a gate:

class UserController extends Controller
{
    public function destroy()
    {
        $this->authorize('role', 'admin');
    }
}

Or in the constructor of a controller:

class ManagerDashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware('role:manager');
    }
}

If the middleware check fails, a 403 response will be returned.

Check roles on a user

Call hasRole on the user model:

// check a single role
$user->hasRole('foo');

// check whether any role exists
$user->hasRole(['bar', 'baz']);

// get all roles
$user->roles;

Conditionally showing content with the blade directive

@role('admin')
<div>Super secret admin stuff goes here...</div>
@endrole

Sharing roles with UI (Inertiajs example)

// AppServiceProvider.php
Inertia::share([
    'auth' => function () {
        return [
            'user' => Auth::user() ? [
                'id' => Auth::user()->id,
                'roles' => Auth::user()->roles->pluck('name'),
            ] : null
        ];
    }
]);
// app.js
Vue.mixin({
  methods: {
    hasRole: function(role) {
      return this.$page.auth.user.roles.includes(role)
    }
  }
})
<!-- SomeComponent.vue -->
<div v-if="hasRole('manager')">I am a manager</div>

Upgrading from v1 to v2

Please see upgrading from v1 to v2 for details and instructions to avoid any issues after upgrading to v2.

Contributing

Please see contributing.md for details and a todolist.

Security

If you discover any security related issues, create an issue on GitHub.

Credits

License

MIT. Please see the license file for more information.

About Coding Labs

Coding Labs is a web app development agency based on the Gold Coast, Australia. See our open source projects on our website.

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.