Using 5.1 Authorization without models

Submitted by Riari - 8 years ago

The Authorization feature that was introduced in 5.1.11 is designed around the idea of associating models with policies, but sometimes you want to be able to define an encompassing policy to check for capabilities at a higher level, in which case checking against models might not make sense. This trick allows defining abilities in the gate based on the methods defined in a policy class.

// 1) Create your policy
class AdminPolicy
{
    ...
    
    public function managePages($user)
    {
        return $user->hasRole(['Administrator', 'Content Editor']);
    }
    
    ...
}

// 2) Define abilities in your AuthServiceProvider

    ...

    /**
     * Register any application authentication / authorization services.
     *
     * @param  \Illuminate\Contracts\Auth\Access\Gate  $gate
     * @return void
     */
    public function boot(GateContract $gate)
    {
        foreach (get_class_methods(new \App\Policies\AdminPolicy) as $method) {
            $gate->define($method, "App\Policies\AdminPolicy@{$method}");
        }
        
        $this->registerPolicies($gate);
    }
    
    ...

// 3) Use conventionally
$this->authorize('managePages'); // in controllers
@can('managePages') // in Blade
$user->can('managePages'); // via Eloquent