Яндекс.Метрика
qr-код - Как-то так стрелка - Как-то так
Ведущий экономист + ... пиктограмма - Как-то Так THIS     Экономическая грамотность и web-решения
Будь в курсе: что, как и почему. Актуальные вещи - своими словами.
Повышайте своё качество с нами - СПЭМ !
If you don't like what you get, change what you give. © Carlos Castaneda     KAKTOTAK.BY - услуги по экономическому проектированию и web-разработке (php/js - telegram, WordPress, Laravel, Vue, SEO)    Cooperation - on an ongoing basis    Be in the topic   -    SUBSCRIBE      My notes are ECONOMICS +  и  Справочник WEB-разработчика | php+js+seo   в Telegram   telegram  

Gates in Laravel - distribution of roles and access rights to project functions: how the mechanism works

Gates in Laravel - distribution of roles and access rights to project functions: how the mechanism works

Laravel has such a cool feature as the Gate Facade, which allows you to set certain rules at the level of any project created on Laravel, according to which the user can get access rights to one or another of its functionality, pages, blocks.

Let's consider the possibilities of Gates in our project, built on the Laravel Breeze ecosystem and including the Vue+ build Inertiajs by default.

The Laravel Breeze system itself provides a ready-made option out of the box, a kind of skeleton for building your project, where there is already a registration and authorization system, which is very great for a quick start in the development of your CRM system, especially together with Vue and Inertiajs

Gate is a laravel facade (service) responsible for proxying calls to Illuminate/Auth/Access/Gate.php through which the mechanism for determining access rights to a particular functionality of the project being created is implemented.

That is, to put it simply, then somewhere and somehow we set a truth condition in the framework for certain/specific users. After that, Laravel will always check for the possibility of their access to something in our project.  

How it works in a simple example.

We installed project Laravel Breeze + Vue + Inetiajs.

Let's define our access rule for authorized users to certain pages of our project.

Let's say we allow all registered users with the active = 1 level. In the users table of our database, we created by migration such a field active.

Gates in Laravel - distribution of access rights in the example - 2

Setting the rule for this Gate 'main-admin' in the provider's boot() method

 app/Providers/AuthServiceProvider.php

Gates in Laravel - distribution of access rights for example - 1

main-admin – this name can be any (set by the developer).

In the define method, we define the value for the active field of the User model (its table) value 1, at which Gate 'main-admin' will determine the truth for this condition (boolean type).

Let's define, for example, that the menu items in the header of all pages for registered users will be available only to those with active = 1. Let these be the navigation tabs Clients and Options. And for clients with the active = 0 level, only the User Account tab is available.

All requests for rendering all our project pages will go through the controllerUserListController.php (the corresponding routes/routes are set in web.php )

The file structure of the project is fully implemented on Vue components using the Inertia facade.

Now, before the implementation of access rights with different levels of active, all project pages are available to all users.

Gates in Laravel - distribution of access rights for example - 3

In the main controller (UserListController.php ) responsible for the output of all pages of our project in the constructor, we set the user's truth check function for all methods (its functions).

Gates in Laravel - distribution of access rights by example - 10

That is, if the conditions Gate are met (if user c active = 1), then in the constructor of this controller we redefine the value of the variable $rights from false to true and pass it to the Vue component which will be output when working out the appropriate method (route).

All these components are children, the parent of which AuthenticatedLayout.vue is nothing more than a wrapper for them, which contains the navigation we need.

Gates in Laravel - distribution of access rights for example - 4

For example, the index() method of the controllerUserListController.php renders the Main component.vue, which is a child of AuthenticatedLayout.vue. According to this principle, other child components are displayed for the corresponding route (controller method).

Gates in Laravel - distribution of access rights by example - 11

In order to check whether the corresponding menu item is displayed by condition, the transfer of the variable $rights must be accepted on the side of the parent component (wrapper) of the parent component (AuthenticatedLayout.vue)) in the form of props. Therefore, we will initially pass this component (AuthenticatedLayout.vue) this variable.

Gates in Laravel - distribution of access rights by example - 5_1

After that, we will specify the conditions for displaying menu items:

Gates in Laravel - distribution of access rights in the example - 5_2

That is, if the value of the received variable in props is true (true), we display the item the menu, and vice versa.

To the parent component (AuthenticatedLayout.vue), in which all child components are nested and for the output of which the controller himself is directly responsible, we will pass the variable $rights, which will subsequently be output on his side via props.

Gates in Laravel - distribution of access rights for example - 5

Now let's check how the navigation of our pages is displayed.

Gates in Laravel - distribution of access rights for example - 6

Gates in Laravel - distribution of access rights by example - 7

As you can see, for a user with active = 1, the menu items are displayedClients and Options and their corresponding pages.

Now let's change the value of active to 0, in the users table of our database.

Gates in Laravel - distribution of access rights by example - 8

And let's check what is displayed on the page now.

Gates in Laravel - distribution of access rights for example - 9

As you can see, we have only the tabUser's account.

автор - Михаленко Р.
M R. Автор - kaktotak.by Специализация: финансово-экономическое проектирование - моделирование бизнеса, инвестиционных проектов реального сектора, анализ и оценка эффективности, оптимизация системы управленческих решений.

Широкий спектр web-компетенций для решения задач бизнеса.

Подписывайтесь на мой телеграмм канал - My notes are ECONOMICS +
Повышайте своё качество вместе со мной - что, как и почему в экономике на простом. Микро- и макро аспекты.

А так же - Справочник WEB-разработчика | php+js+seo
Заметки и нативные решения простых локальных задач на PHP, JS. Кое-что про Laravel, WordPress, Vue и SEO.

  Персональная помощь в экономическом проектировании и веб-разработке:

  • Финансово-экономическое моделирование, анализ, учёт, бизнес-планирование
  • Комплексная web-разработка/поддержка проекта в сети (php/js, seo – Laravel, WordPress, Vue, telegram, администрирование, контент, реклама в Яндекс Директ

  telegram или форма обратной связи

Administrator
180

Currency Converter
RUB RUB-icon
USD USD-icon
EUR EUR-icon
CNY CNY-icon
BYN BYN-icon
UAH UAH-icon
KZT KZT-icon
ЗАМЕТКИ ЭКОНОМИСТА
SHORT- what is it about
ECONOMIC LITERACY
  Simple online solutions to problems of economics and finance  
I Want To Know Everything. Useful Tips