Realization of ACL user authorization and authority check function in Laravel 5.1 framework

01-28-2024

This article is about the realization of ACL user authorization and authority check function in Laravel 5.1 framework, which has certain reference value and hopes to help friends in need. 1. Introduction

The out-of-the-box authentication function provided by Laravel makes it convenient and simple for users to register, log in, log out and reset their passwords.

But if you need to control access to specific parts of the site, or let non-administrators open/close specific pages, or ensure that some users can only edit their own published things (such as articles), then you need to introduce tools like BeatSwitch Lock or write such functions manually. We call such a function ACL:Access Control Lists, which is used to define users' rights to operate or view specific things based on their user record attributes.

Fortunately, starting from Laravel 5.1.11, Laravel has provided out-of-the-box authorization function to realize the above requirements, and we don't need to do any extra work, just use it.

Note: Before starting this section, please refer to the upgrade guide to upgrade Laravel to Laravel 5.1.11, otherwise the related functions will not be realized.

2. What can I do?

The out-of-the-box ACL provided by Laravel is called Gate (this is not a product name similar to Spark, but just the name of a class and facade).

Using the Gate class (injecting or using the Gate facade) allows us to easily check whether a user (currently logged in user or specified user) is allowed to operate certain things. Check code is as follows:

if (Gate::denies('update-post', $post)) { abort(403); }

Put this code into the controller, and it will use the defined rule update-post to check whether the current authenticated user has the right to update the specified article.

You can also use Gate::allows, which is opposite to denies method, and you can also use it through @can in the Blade view template, and more, let's take a look at it next.

3. How to use it?

Laravel ACL is based on the concept of permission, which includes a key (such as update-post) and a closure (which can pass in parameters) that returns true or false.

3.1 define permissions

Let's define the user's permission to update the article update-post in AuthServiceProvider as follows:

Copyright Description:No reproduction without permission。

Knowledge sharing community for developers。

Let more developers benefit from it。

Help developers share knowledge through the Internet。

Follow us