PHP code example of sergmoro1 / laravel-rbac

1. Go to this page and download the library: Download sergmoro1/laravel-rbac 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/ */

    

sergmoro1 / laravel-rbac example snippets


php artisan vendor:publish --tag=rbac-sample



namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Yiisoft\Access\AccessCheckerInterface;
use Yiisoft\Rbac\Manager;
use Yiisoft\Rbac\SimpleRuleFactory;
use Yiisoft\Rbac\Php\AssignmentsStorage;
use Yiisoft\Rbac\Php\ItemsStorage;
use Yiisoft\Rbac\Rules\Container\RulesContainer;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->app->bind(AccessCheckerInterface::class, function ($app) {
            $directory = __DIR__ . '/../../storage/rbac';

            $itemsStorage = new ItemsStorage($directory . '/items.php');
            $assignmentsStorage = new AssignmentsStorage($directory . '/assignments.php');
            $rulesContainer = new RulesContainer(app());
    
            return new Manager($itemsStorage, $assignmentsStorage, $rulesContainer);
        });
    }
}

php artisan rbac:init



namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Yiisoft\Access\AccessCheckerInterface;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;

    public function __construct(private AccessCheckerInterface $accessChecker)
    { 
    }

    /**
     * Checking the permission to perform the action.
     * 
     * @param string $action
     * @param array $params
     */
    protected function checkAccess(string $action, $params = [])
    {
        $userId = auth()->id();
        if (!$this->accessChecker->userHasPermission($userId, $action, $params)) {
            abort(403, 'Access denied');
        }
    }
}



namespace App\Http\Controllers;

class PostController extends Controller
{
    public function create()
    {
        $this->checkAccess('createPost');
        
        $post = new Post();
        $post->status = Post::STATUS_DRAFT;

        return view('post', ['post' => $post, 'action' => 'create']);
    }

    public function edit(int $id)
    {
        $post = Post::find($id);

        $this->checkAccess('updatePost', ['user_id' => $post->user_id]);
        
        return view('post', ['post' => $post, 'action' => 'edit']);
    }