PHP code example of dynamik-dev / laravel-policy-engine

1. Go to this page and download the library: Download dynamik-dev/laravel-policy-engine 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/ */

    

dynamik-dev / laravel-policy-engine example snippets


Marque::createRole('admin', 'Admin')
    ->grant(['members.*', 'posts.*'])
    ->assignTo($user, scope: $acmeTeam);

Marque::createRole('viewer', 'Viewer')
    ->grant(['posts.read'])
    ->assignTo($user, scope: $widgetTeam);

$user->can('members.remove', $acmeTeam);  // true
$user->can('members.remove', $widgetTeam); // false

$user->assignRole('editor', $acmeOrg);

$user->can('posts.create', $acmeOrg); // true

Route::middleware('can:posts.create')->post('/posts', [PostController::class, 'store']);

Marque::createRole('editor', 'Editor')
    ->grant(['posts.*', 'comments.*'])
    ->deny(['posts.delete']);

$editor->can('posts.create');  // true
$editor->can('posts.delete');  // false -- deny wins

Marque::boundary($freeOrg)->permits(['posts.read', 'comments.read']);
Marque::boundary($proOrg)->permits(['posts.*', 'comments.*', 'analytics.*']);

$user->assignRole('admin', $freeOrg);
$user->can('analytics.view', $freeOrg);  // false -- boundary blocks it
$user->can('analytics.view', $proOrg);   // true

'posts.*'           // all post actions
'*.read'            // read anything
'*.*'               // superadmin
'posts.update.own'  // fine-grained qualifiers

Marque::resource(Post::class)
    ->allow('update')
    ->when(fn ($user, $post) => $post->author_id === $user->id);

Marque::resource(Post::class)
    ->deny('delete');