Skip to content

Instantly share code, notes, and snippets.

@me7media
Created October 1, 2019 14:14
Show Gist options
  • Save me7media/4e17d0b34daeb9cf6ba131f4dafe0f86 to your computer and use it in GitHub Desktop.
Save me7media/4e17d0b34daeb9cf6ba131f4dafe0f86 to your computer and use it in GitHub Desktop.
Laravel User Roles Permissions
<?php
namespace App\Providers;
use App\Permission;
use Cache;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any application authentication / authorization services.
*
* @param \Illuminate\Contracts\Auth\Access\Gate $gate
* @return void
*/
public function boot(GateContract $gate)
{
//Отключаем Проверку если команда из Консоли
if (\App::runningInConsole()) {
echo 'Running in console (i.e. migration). Disabling AuthServiceProvider' . PHP_EOL;
return;
}
parent::registerPolicies($gate);
try {
$permission_arguments = ['access', 'view', 'create', 'edit', 'delete'];
//// Dynamically register permissions with Laravel's Gate.
$permissions = $this->getPermissions();
foreach ($permissions as $permission) {
foreach ($permission_arguments as $value) {
$gate->define($permission->value . '.' . $value, function ($user) use ($permissions, $permission, $value) {
foreach ($permissions->where('role_id', $user->role_id)->where('value', $permission->value) as $item) {
return $item->{$value};
}
});//gate
} // foreache ARG
} // foreache ENTITIES
} catch (QueryException $e) {
return false;
}
}
/**
* Fetch the collection of site permissions.
*
* @return \Illuminate\Database\Eloquent\Collection
*/
protected function getPermissions()
{
return Cache::remember('permissions', '60', function () {
return Permission::all();
});
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Permission extends Model
{
protected $fillable = ['name', 'value', 'role_id', 'access', 'view', 'create', 'edit', 'delete'];
public function roles()
{
return $this->belongsTo(Role::class, 'role_id');
}
}
//User Modal
class User extends Authenticatable
{
use Notifiable;
protected $fillable = ['name', 'email', 'phone', 'password', 'remember_token', 'role_id', 'related_id'];
protected $hidden = ['password', 'remember_token'];
// Доступ и Разрешения
public function can($ability, $arguments = [])
{
abort_if(!Gate::allows($ability), 401);
}
Uses
blade
@can('orders.create')
controller
abort_if(!Gate::allows('orders.create'), 401);
or if($user->can('orders.create')){...};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment