PHP code example of szykra / laravel-guard

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/ */

    

szykra / laravel-guard example snippets


Schema::create('roles', function(Blueprint $table)
{
    $table->increments('id');
    $table->string("tag", 20);
    $table->string("name", 100);
});

Schema::create('permissions', function(Blueprint $table)
{
    $table->increments('id');
    $table->string("tag", 50);
    $table->string("name", 50);
    $table->string("description");
});

Schema::create('permission_role', function(Blueprint $table)
{
    $table->increments('id');
    $table->unsignedInteger('role_id');
    $table->unsignedInteger('permission_id');

    $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
    $table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
});

Schema::update('users', function(Blueprint $table)
{
    $table->unsignedInteger('role_id');

    $table->foreign('role_id')->references('id')->on('roles');
});

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]);
            }
        }
    }
}

/* String */
$router->get('/users', [
	'as' => 'users.index',
	'uses' => 'UsersController@index',
	'needs' => 'USERS.READ'
]);

/* As array */
$router->get('/users/{id}', [
	'as' => 'users.show',
	'uses' => 'UsersController@show',
	'needs' => ['USERS.READ']
]);

/* String - separate by pipe */
$router->post('/users', [
	'as' => 'users.store',
	'uses' => 'UsersController@store',
	'needs' => 'USERS.READ|USERS.CREATE'
]);

/* As array */
$router->put('/users', [
	'as' => 'users.update',
	'uses' => 'UsersController@update',
	'needs' => ['USERS.READ', 'USERS.CREATE']
]);

$router->put('/users', [
	'as' => 'users.update',
	'uses' => 'UsersController@update',
	'needs' => ['USERS.READ', 'USERS.CREATE'],
	'middleware' => 'guard'
]);

$router->group(['needs' => ['USERS.READ']], function() use ($router)
{
    // Needs USERS.READ permission
    $router->get('/users/{id}', [
        'as' => 'users.show',
        'uses' => 'UsersController@show',
    ]);

    // Needs USERS.READ and USERS.UPDATE permissions
    $router->put('/users/{id}', [
        'as' => 'users.update',
        'uses' => 'UsersController@update',
        'needs' => ['USERS.UPDATE']
    ]);
});

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
    }

}

<section class="actions">
    <a href="{{ route('users.show', $user->id) }}">Show</a>

    @if(Auth::user()->can('USERS.EDIT'))
        | <a href="{{ route('users.edit', $user->id) }}">Edit</a>
    @endif
</section>

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);
}

'guard' => 'Szykra\Guard\Middleware\ProtectRoutes'
sh
php artisan guard:make:role ADMIN Administrator
sh
php artisan guard:make:permission USERS.READ
sh
php artisan guard:grant ADMIN USERS.READ