PHP code example of authority-php / authority-laravel
1. Go to this page and download the library: Download authority-php/authority-laravel 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/ */
authority-php / authority-laravel example snippets
// config/authority.php
return array(
'initialize' => function($authority) {
$user = $authority->getCurrentUser();
// action aliases
$authority->addAlias('manage', array('create', 'read', 'update', 'delete'));
$authority->addAlias('moderate', array('read', 'update', 'delete'));
// an example using the `hasRole` function, see below examples for more details
if ($user->hasRole('admin')){
$authority->allow('manage', 'all');
}
}
);
php artisan vendor:publish
php artisan migrate
// app/User.php
public function roles() {
return $this->belongsToMany('App\Authority\Role');
}
public function permissions() {
return $this->hasMany('App\Authority\Permission');
}
public function hasRole($key) {
foreach ($this->roles as $role) {
if ($role->name === $key) {
return true;
}
}
return false;
}
// app/Authority/Role.php
use Illuminate\Database\Eloquent\Model;
class Role extends Model {}
// app/Authority/Permission.php
use Illuminate\Database\Eloquent\Model;
class Permission extends Model {}
// config/authority.php
return array(
'initialize' => function($authority) {
$user = $authority->getCurrentUser();
// action aliases
$authority->addAlias('manage', array('create', 'read', 'update', 'delete'));
$authority->addAlias('moderate', array('read', 'update', 'delete'));
// an example using the `hasRole` function, see below examples for more details
if ($user->hasRole('admin')) {
$authority->allow('manage', 'all');
}
// loop through each of the users permissions, and create rules
foreach ($user->permissions as $perm) {
if ($perm->type == 'allow') {
$authority->allow($perm->action, $perm->resource);
} else {
$authority->deny($perm->action, $perm->resource);
}
}
}
);
// If you added the alias to `config/app.php` then you can access Authority, from any Controller, View, or anywhere else in your Laravel app like so:
if (Authority::can('create', 'User')) {
User::create(array(
'username' => '[email protected]'
));
}
// If you just chose to use the service provider, you can use the IoC container to resolve your instance
$authority = App::make('authority');