PHP code example of dlnsk / h-rbac

1. Go to this page and download the library: Download dlnsk/h-rbac 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/ */

    

dlnsk / h-rbac example snippets


if (\Gate::allows('edit', $post)) { /* do something */ }
...
if (\Gate::denies('edit', $post)) { abort(403); }
...
if (\Gate::forUser($user)->allows('edit', $post)) { /* do something */ }

if ($request->user()->can('edit', $post)) { /* do something */ }
...
if ($request->user()->cannot('edit', $post)) { abort(403); }

$this->authorize('edit', $post);

$this->authorize('edit', $post);
$this->authorize('create', Post::class);

$this->authorize('download', ReportPolicy::class);

$this->authorize('download', [ReportPolicy::class, 'current_date' => Carbon::now()]);

$this->authorize('download', ['current_date' => Carbon::now(), 'policy' => ReportPolicy::class]);

class PostPolicy
{
    public $chains = [
        'edit' => [
            'editAnyPost',
            'editPostInCategory',
            'editOwnPost',
        ],
        'delete' => [
            'deleteAnyPost',
            'deleteOwnPost',
        ],
    ];

    ////////////// Callbacks ///////////////

    public function editOwnPost($user, $post) {
        return $user->id === $post->user_id;
    }

    public function editPostInCategory($user, $post, $permissions): bool {
        return $permissions && $permissions->contains('value', $post->category_id);
    }
}
 php
public function editOwnPost($user, $post) {
    return $user->id === $post->user_id;
}
 php
if (\Gate::can('editOwnPost', $post)) {
}
 php
if (\Gate::can('edit', $post)) {
}
 php
public function getRolesAttribute() {
    return $this->roles()->pluck('name')->toArray();
}
 php
public function editPostInCategory($user, $post, $permissions): bool {
    return $permissions && $permissions->contains('value', $post->category_id);
}
 php
 return [
    /**
     * Built-in application roles and its permissions
     */
    'builtinRoles' => [
        'manager' => [
            'editAnyPost',
            'deleteAnyPost',
            'seeReportsInCategory',
        ],
        'user' => [
            'editOwnPost',
            'seeOwnReports',
        ],
    ],

];