l5starter / permission-manager by wiwatsrt

Laravel 5 Start, Package permission manager
103
0
2
Package Data
Maintainer Username: wiwatsrt
Maintainer Contact: wiwat_srt@hotmail.com (Wiwat Srisattha)
Package Create Date: 2016-09-23
Package Last Update: 2017-12-28
Language: PHP
License: MIT
Last Refreshed: 2024-11-18 03:02:35
Package Statistics
Total Downloads: 103
Monthly Downloads: 0
Daily Downloads: 0
Total Stars: 0
Total Watchers: 2
Total Forks: 0
Total Open Issues: 0

L5Starter\PermissionManagement

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 () {
    //
});