M
M
Mazino2018-12-21 13:13:17
Laravel
Mazino, 2018-12-21 13:13:17

How to create an abstract Gate::define() in Laravel?

How to create a generic action authorization function via Gate::define()?
Example:

//AuthServiceProvider.php

public function boot()
    {
        $this->registerPolicies();
        $this->registerUserPermissionPolicies();
    }

    public function registerUserPermissionPolicies()
    {
        Gate::before(function($user, $ability) {
            if ($user->isSuperAdmin()) {
                return true;
            }
        });

        Gate::define($ability, function($user, $ability) {
            return $user->hasAccess($ability);
        });
    }

How to force ) to pass to your string so that it works, by analogy with:@can('ability'$ability
//AuthServiceProvider.php
Gate::define('ability', function($user) {
    return $user->hasAccess('ability');
});

//Anywhere.blade.php
@can('ability')
//Something
@endcan

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Sokharev, 2018-12-21
@Mazino

Gate::before(function ($user, $ability) {
    return $user->hasAccess($ability);
});

However, it should be understood that all other gateways will stop working.
Therefore, one can first check if such a "capability" is present in the list of valid "configurable capabilities"
Gate::before(function ($user, $ability) {
   if(in_array($ability,  ['see_private_posts', 'delete_private_posts'])) {
       return $user->hasAccess($ability);
   }
});

In other words, if the closure passed to the before method returns a boolean value, then that value will be taken into account. If it is void/null, then it will not be taken into account.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question