1. Go to this page and download the library: Download back2lobby/access-control 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/ */
back2lobby / access-control example snippets
// Give a role some permission
AccessControl::allow("manager")->to('edit-company');
// Assign role to any user
AccessControl::assign('manager')->to($user);
// You can also assign role for a specific roleable model
AccessControl::assign('manager',$company)->to($user);
// Checking the permission on user for a roleable model
AccessControl::canUser($user)->do("edit-company",$company);
// Checking if the user has a role for that model
AccessControl::is($user)->a("manager",$company);
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Back2Lobby\AccessControl\Traits\HasRoles;
class User extends Authenticatable
{
use HasFactory, HasRoles
// code here
}
use Back2Lobby\AccessControl\Traits\Roleable;
class Post extends Model
{
use Roleable;
}
use Illuminate\Database\Seeder;
use Back2Lobby\AccessControl\Facades\AccessControlFacade as AccessControl;
class AccessControlSeeder extends Seeder
{
public function run()
{
// Create all roles
AccessControl::createManyRoles([
[
'name' => 'admin',
'title' => 'Administrator',
],
[
'name' => 'editor',
'title' => 'Editor',
]
]);
// Create all permissions
AccessControl::createManyPermissions([
[
'name' => 'create-post',
'title' => 'Create Post',
'description' => 'Allows user to create a new post',
],
[
'name' => 'edit-post',
'title' => 'Edit Post',
'description' => 'Allows user to edit an existing post',
],
]);
}
}
AccessControl::createRole([
'name' => 'manager',
'title' => 'Manager',
'roleables' => [Company::class]
]);
// ✓ assigning role with allowed roleable will work fine
$user->assign('manager',$company);
// ✗ assigning role with roleable that's not allowed will throw error
$user->assign('manager',$post);
// using role name
AccessControl::updateRole('author',[
'name' => 'post-author',
'title' => 'Post Author'
]);
AccessControl::deleteRole('author');
AccessControl::getRole('admin');
AccessControl::getAllRoles();
AccessControl::allow('author')->to('edit'); // with permission name
AccessControl::allow('author')->to($permission); // with permission object
AccessControl::allow('author')->to(3); // with permission id