l5starter/permission-manager

Laravel 5 Start, Package permission manager

dev-master 2017-12-28 11:27 UTC

This package is not auto-updated.

Last update: 2024-11-09 19:20:00 UTC


README

Installation

In order to install Laravel 5, just add

"l5starter/permission-manager": "5.4.x-dev"

to your composer.json. Then run composer install or composer update.

Then in your config/app.php add in providers

Spatie\Permission\PermissionServiceProvider::class,
L5Starter\PermissionManager\PermissionManagerServiceProvider::class,

You can publish the migration with

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="migrations"

Running Migrations

$ php artisan migrate

You can publish the seeders with

php artisan vendor:publish --provider="L5Starter\PermissionManager\PermissionManagerServiceProvider" --tag="seeder"

Running Seeders

$ php artisan db:seed --class=RolesTableSeeder

Add menu in resources/views/vendor/l5starter/admin/partials/sidebar.blade.php

<li class="{{ (Request::is('admin/roles*') ? 'active' : '') }}">
    <a href="{{ route('admin.roles.index') }}">
        <i class="fa fa-users"></i> <span>{{ trans('l5starter::general.roles') }}</span>
    </a>
</li>
<li class="{{ (Request::is('admin/permissions*') ? 'active' : '') }}">
    <a href="{{ route('admin.permissions.index') }}">
        <i class="fa fa-cog"></i> <span>{{ trans('l5starter::general.permissions') }}</span>
    </a>
</li>

Usage

First add the Spatie\Permission\Traits\HasRoles-trait to your User model.

use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;

    // ...
}

Using a middleware

The package doesn't contain a middleware to check permissions but it's very trivial to add this yourself.

$ php artisan make:middleware RoleMiddleware

This will create a RoleMiddleware for you, where you can handle your role check.

// app/Http/Middleware/RoleMiddleware.php
use Auth;

...

public function handle($request, Closure $next, $role)
{
    if (Auth::guest()) {
        return redirect($urlOfYourLoginPage);
    }

    if (! $request->user()->hasRole($role)) {
       abort(403);
    }

    return $next($request);
}

Don't forget to add the route middleware to your Kernel:

// app/Http/Kernel.php
protected $routeMiddleware = [
    ...
    'role' => \App\Http\Middleware\RoleMiddleware::class,
    ...
];

Now you can protect your routes using the middleware you just set up:

Route::group(['middleware' => ['role:admin']], function () {
    //
});