1. Go to this page and download the library: Download nematollahi/laravel-acl 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/ */
//app/Models/User.php
use Nematollahi\ACL\Traits\HasACLTools;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable , HasACLTools;
enother codes ...
trait ACLTools
{
protected array $userPermissions = []; // It stores all the user's permissions in itself (role + permission )
public function roles() // get all current user roles
{
return $this->belongsToMany(Config::get("acl.role"));
}
public function permissions() // get all permissions user permissions
{
return $this->belongsToMany(Config::get("acl.permission"));
}
public function hasRoles(...$roles): bool //Checks if the user already has these roles
{
foreach ($roles as $role) {
if ($this->roles->contains("name", $role)) {
return true;
}
}
return false;
}
public function hasPermission($permission): bool //This method checks whether the user currently has the permissions
{
$accessPermission = $this->setPermissions();
if (in_array($permission, $accessPermission)) {
return true;
}
return false;
}
protected function setPermissions(): array //Initializes the userPermissions variable
{
//We put a loop on all the user roles and put all the permissions that exist in it into the userPermissions variable
foreach ($this->roles as $role) {
foreach ($role->permissions as $permission) {
array_push($this->userPermissions, $permission->name);
}
}
//We put all permissions in the userPermissions variable
foreach ($this->permissions as $permission) {
array_push($this->userPermissions, $permission->name);
}
return $this->userPermissions;
}
}
class ACL implements IACL
{
use ACLTools;
public static function run()
{
$modelPermission = Config::get("acl.permission");
(new $modelPermission)->all()->map(function ($permission) {
Gate::define($permission->name, function (User $user) use ($permission) {
return $user->hasPermission($permission->name);
});
});
}
}
public function boot()
{
ACL::run();
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.