1. Go to this page and download the library: Download szykra/laravel-guard 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/ */
use Szykra\Guard\Contracts\Permissible;
use Szykra\Guard\Traits\Permissions;
class User extends Model implements Permissible, AuthenticatableContract, CanResetPasswordContract {
use Permissions, Authenticatable, CanResetPassword;
public function role()
{
return $this->belongsTo('Szykra\Guard\Models\Role');
}
}
'Szykra\Guard\GuardServiceProvider'
'Szykra\Guard\Middleware\ProtectRoutes',
use Szykra\Guard\Models\Permission;
use Szykra\Guard\Models\Role;
use Illuminate\Database\Seeder;
class GuardTableSeeder extends Seeder
{
public function run()
{
$roles = [
'ADMIN' => 'Administrator',
'EDITOR' => 'Content Editor'
];
$permissions = [
['tag' => 'POSTS.CREATE', 'name' => 'Create posts', 'description' => 'Ability to create new post'],
['tag' => 'POSTS.READ', 'name' => 'Read posts', 'description' => 'Ability to read posts data'],
['tag' => 'POSTS.UPDATE', 'name' => 'Update posts', 'description' => 'Ability to update posts data'],
['tag' => 'POSTS.DELETE', 'name' => 'Delete posts', 'description' => 'Ability to delete posts']
];
$permModels = [];
foreach ($permissions as $perm) {
$permModels[$perm['tag']] = Permission::create($perm);
}
$rolesToPerm = [
'ADMIN' => ['POSTS.CREATE', 'POSTS.READ', 'POSTS.UPDATE', 'POSTS.DELETE'],
'EDITOR' => ['POSTS.CREATE', 'POSTS.READ', 'POSTS.UPDATE']
];
foreach ($rolesToPerm as $tag => $permissions) {
$name = $roles[$tag];
$role = Role::create(compact('tag', 'name'));
foreach ($permissions as $perm) {
$role->permissions()->save($permModels[$perm]);
}
}
}
}
use Szykra\Guard\Contracts\Permissible;
class UsersController extends Controller {
public function __construct(Permissible $user)
{
$this->user = $user;
}
public function update(Request $request, $id)
{
if( ! $this->user->can('USERS.UPDATE')) {
// redirect, exception, flash message, etc.
}
// do something with user
}
}
use Szykra\Guard\Contracts\Permissible;
class UsersController extends Controller {
public function destroy(Permissible $user, $id)
{
if( ! $user->can('USERS.DELETE')) {
// redirect, exception, flash message, etc.
}
// destroy user
}
}
use Szykra\Guard\Contracts\Permissible;
class CreateUserRequest extends Request {
public function authorize(Permissible $user)
{
return $user->can("USERS.CREATE");
}
public function rules()
{
return [
// your validation rules
];
}
}
public function render($request, Exception $e)
{
if($e instanceof InsufficientPermissionException) {
Flash::warning("Insufficient permissions", "You don't have enough permission to access to this section.");
return redirect()->route('home');
}
return parent::render($request, $e);
}