PHP code example of damiantw / laravel-roles

1. Go to this page and download the library: Download damiantw/laravel-roles library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

damiantw / laravel-roles example snippets


        /*
         * Package Service Providers...
         */
        DamianTW\LaravelRoles\Providers\RoleServiceProvider::class,



namespace App;

use DamianTW\LaravelRoles\Traits\HoldsAuthorities;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;
    use HoldsAuthorities;
    
    //...

    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'hasAuthority' => \DamianTW\LaravelRoles\Middleware\HasAuthority::class,
        'hasAuthorityController' => \DamianTW\LaravelRoles\Middleware\HasAuthorityController::class
        // ...
    ];



namespace App\Policies;

use App\User;
use App\Post;
use Illuminate\Auth\Access\HandlesAuthorization;

class PostPolicy
{
    use HandlesAuthorization;
    
    public function before($user, $ability)
    {
        //If the User has the SUPER_ADMIN authority they will always pass all Policy checks
        if ($user->hasAuthority('SUPER_ADMIN')) {
            return true;
        }
    }

    public function view(User $user, Post $post)
    {
        // To view a Post:
        // A User must have the authority POST_SHOW
        // and cannot view private Posts unless they are their own.
        return $user->hasAuthority('POST_SHOW') && (!$post->private || $user->id === $post->user_id);
    }

    public function create(User $user)
    {
        // To create a Post:
        // A User must have the authority POST_CREATE **AND** POST_STORE
        return $user->hasAllAuthorities(['POST_CREATE', 'POST_STORE']);
    }

    public function update(User $user, Post $post)
    {
        // To update a Post:
        // A user must have the authority POST_EDIT **OR** POST_UPDATE
        // and can only edit their own Posts
        return $user->hasAnyAuthority(['POST_EDIT', 'POST_UPDATE']) && $user->id === $post->user_id;
    }

    public function delete(User $user, Post $post)
    {
        // To delete a Post:
        // A user must have the authority POST_DESTROY
        // and either must be deleting their own Post or have the authority POST_CLEANER
        return $user->hasAuthority('POST_DESTROY') && ($user->id === $post->user_id || $user->hasAuthority('POST_CLEANER'));
    }
}



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class PostController extends Controller
{
    
    public function create()
    {
        $this->authorize('create', Post::class);
        //...
    }

    public function store(Request $request)
    {
        $this->authorize('create', Post::class);
        //...
    }

    public function show(Post $post)
    {
        $this->authorize('view', $post);
        //...
    }

    public function edit(Post $post)
    {
        $this->authorize('update', $post);
        //...
    }

    public function update(Request $request, Post $post)
    {
        $this->authorize('update', $post);
        //...
    }

    public function destroy(Post $post)
    {
        $this->authorize('delete', $post);
        //...
    }
}



// User must have the USER_UPDATE authority to access the route
Route::put('/user/{user}', 'UserController@update')->middleware('hasAuthority:USER_UPDATE');

// More then one authority can be specificed using the pipe.
// If the user has the authority USER_DESTROY **OR** USER_MODERATOR they will be allowed access to the route
Route::delete('/user/{user}', 'UserController@destroy')->middleware('hasAuthority:USER_DESTROY|USER_MODERATOR');
 
// Apply **AND** boolean logic by calling the hasAuthority middleware multiple times
// Allowed if $user->hasAnyAuthority(['USER_VIEW','USER_SHOW']) **AND** $user->hasAuthority(['ADMIN']);
Route::get('/user/{user}', 'UserController@show')->middleware('hasAuthority:USER_VIEW|USER_SHOW', 'hasAuthority:ADMIN');

//You can provide a second parameter to define the guard that should be used to retreive the authenticated user
//The web guard will be used by default
Route::put('/user/{user}', 'UserController@update')->middleware('hasAuthority:USER_UPDATE,api');
 



namespace App\Http\Controllers;

class PostController extends Controller
{
    function __construct() 
    {
        // Optionally provide a guard parameter to hasAuthorityController. 
        // The web guard will be used by default
        // ex: $this->middleware('hasAuthorityController:api');   
        $this->middleware('hasAuthorityController');    
    }
    public function create(){}
    public function store(){}
    public function show(){}
    public function edit(){}
    public function update(){}
    public function destroy(){}
}



// Returns true only if $authorityStr is in the User's authority set.
$user->hasAuthority($authorityStr);

// Returns true only if $authorityStr1 **OR** $authorityStr2 is in the User's authority set.
$user->hasAnyAuthority([$authorityStr1, $authorityStr2]);

// Returns true only if $authorityStr1 **AND** $authorityStr2 **AND** $authorityStr3 are in the User's authority set.
$user->hasAllAuthorities([$authorityStr1, $authorityStr2, $authorityStr3]);

// Returns a Collection of all the User's authorities
$user->authorities();

// Eloquent relation for User Roles.
$user->roles;
$user->roles();

// Eloquent relation for User RoleGroups
$user->roleGroups;
$user->roleGroups();



use Illuminate\Database\Seeder;
use DamianTW\LaravelRoles\Facades\RoleGroupSeeder;
use App\RoleGroup;

class RoleGroupsTableSeeder extends Seeder
{
    
    public function run()
    {
        $admin = RoleGroup::firstOrCreate(['name' => 'Admin']);
        $user = RoleGroup::firstOrCreate(['name' => 'User']);
        
        RoleGroupSeeder::defineRoleGroupAuthorities(
          [
              $admin->id => [
                  'VIEW_USER',
                  'CREATE_USER',
                  'UPDATE_USER',
                  'DELETE_USER'
              ],
              // Admin RoleGroup will have authorities: VIEW_USER, CREATE_USER, UPDATE_USER, DELETE_USER
              
              $user->id => [
                  'ViEW_USER'
              ]
              // User RoleGroup will only have the VIEW_USER authority 
          ]  
        );
    }
}



namespace App\Http\Controllers;

class PostController extends Controller
{
    function __construct() {}
    public function create(){}
    public function store(){}
    public function show(){}
    public function edit(){}
    public function update(){}
    public function destroy(){}
    private function privateHelperFunction(){}
}

        RoleGroupSeeder::defineRoleGroupAuthorities(
          [
              $group->id => [
                  'NON_CONTROLLER_BASED_AUTHORITY',
                  App\Http\Controllers\PostController::class,
              ],
          ]  
        );

    php artisan make:policy PostPolicy --model=Post