Introduction to the

Gates is a closure function that determines whether a user has permission to perform an action.

define

Gates is usually defined in AppProvidersAuthServiceProvider.

The first argument to Gates is a user instance. It supports optional arguments, such as the Eloquent model:

public function boot() { $this->registerPolicies(); Gate::define('edit-settings', function ($user) {return $user->isAdmin; }); Gate::define('update-post', function ($user, $post) {return $user->id === $post->user_id; }); } public function boot() { $this->registerPolicies(); Gate::define('update-post', 'AppPoliciesPostPolicy@update'); }Copy the code

use

If (Gate::allows('edit-settings')) {// Current user can edit Settings} if (Gate::allows('update-post', $post) {// If (Gate:: Denies ('update-post', $post)) {if (Gate::forUser($user)->allows('update-post', $post) {// If (Gate::forUser($user)->denies('update-post', $post) {// If (Gate::forUser)->denies('update-post', $post)Copy the code

Parameter context

Gate::define('create-post', function ($user, $category, $extraFlag) {
    return $category->group > 3 && $extraFlag === true;
});
if (Gate::check('create-post', [$category, $extraFlag])) {
    // The user can create the post...
}
Copy the code

Authorization response

use IlluminateSupportFacadesGate; use IlluminateAuthAccessResponse; Gate::define('edit-settings', function ($user) { return $user->isAdmin ? Response::allow() : Response::deny('You must be a super administrator.'); }); $response = Gate::inspect('edit-settings', $post); If ($response->allowed()) { } else { echo $response->message(); }Copy the code

Authorized to intercept

Gate::before(function ($user, $ability) {if ($user->isSuperAdmin()) {return true; }}); Gate::after(function ($user, $ability, $result, $arguments) {if ($user->isSuperAdmin()) {return true; }});Copy the code