Home PHP Framework Laravel How to implement permission-based display and hiding of page elements in Laravel

How to implement permission-based display and hiding of page elements in Laravel

Nov 03, 2023 am 08:35 AM
Permission control Page element display Page element hidden

How to implement permission-based display and hiding of page elements in Laravel

In Laravel, it is a common requirement to implement permission-based display and hiding of page elements. This article will introduce how to use Laravel's permission management library "spatie/laravel-permission" to implement the function of dynamically rendering page elements. At the same time, in order to better illustrate the problem, this article will write a simple example program.

1. Install laravel-permission

First, you need to install the "spatie/laravel-permission" composer package in the Laravel project. Use the following command to install:

composer require spatie/laravel-permission
Copy after login

After installation, you need to run migration to create the relevant permission management table:

php artisan vendor:publish --provider="SpatiePermissionPermissionServiceProvider" --tag="migrations"

php artisan migrate
Copy after login

2. Define roles and permissions

In this example , we will define two roles, namely "Administrator" and "General User", and give the administrator the permission to view all data.

First, you need to add the configuration of the role and permission model in the config/auth.php file:

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => AppModelsUser::class,
    ],

    'roles' => [
        'driver' => 'eloquent',
        'model' => SpatiePermissionModelsRole::class,
    ],

    'permissions' => [
        'driver' => 'eloquent',
        'model' => SpatiePermissionModelsPermission::class,
    ],
],
Copy after login

Then, add the relationship with the role and permission in the User model:

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use SpatiePermissionTraitsHasRoles;

class User extends Authenticatable
{
    use HasFactory, HasRoles;

    //...
}
Copy after login

Then you can define roles and permissions in Seeder:

use IlluminateDatabaseSeeder;
use SpatiePermissionModelsPermission;
use SpatiePermissionModelsRole;

class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        //创建角色
        Role::create(['name' => 'admin']);
        Role::create(['name' => 'user']);

        //创建权限
        Permission::create(['name' => 'view_all_data']);

        //管理员拥有所有权限
        Role::findByName('admin')->givePermissionTo(Permission::all());
    }
}
Copy after login

3. Authorization and authentication

Next, use the authorize() method in the controller to determine whether the user Have specific permissions. For example, the following index method requires the "view_all_data" permission:

public function index()
{
    $this->authorize('view_all_data');
    //...
}
Copy after login

In addition, in the view, you can use the can() method to determine whether the current user has a certain permission. For example, in the following code, the "View All Data" button will be displayed only if the user has the "view_all_data" permission:

@if(auth()->user()->can('view_all_data'))
    <button>查看所有数据</button>
@endif
Copy after login

If you want more fine-grained control, you can use the role() method. Determine whether the user has a certain role. For example, in the following code, the "Administrator Menu" will be displayed only when the user has the "admin" role:

@if(auth()->user()->hasRole('admin'))
    <menu>管理员菜单</menu>
@endif
Copy after login

4. Dynamically rendering page elements

Sometimes, the Certain elements need to be rendered dynamically based on the current user's role or permissions. For example, you can set that only administrators can see the "Delete" button:

@if(auth()->user()->can('delete_data'))
    <button>删除</button>
@endif
Copy after login

However, if there are multiple elements that need to be dynamically rendered based on permissions, then each element must be judged individually, which will lead to code duplication and maintenance. Increased costs. At this time, you can encapsulate this function into a Blade command and let it accept a permission name as a parameter:

Blade::directive('can', function ($expression) {
    return "<?php if(auth()->user()->can({$expression})): ?>";
});

Blade::directive('endcan', function () {
    return "<?php endif; ?>";
});
Copy after login

Using this command, you can dynamically render page elements in the following way:

@can('delete_data')
    <button>删除</button>
@endcan
Copy after login

In this way, the code becomes more concise and clear.

Summary

By using Laravel's permission management library "spatie/laravel-permission", we can easily implement permission-based display and hiding of page elements. At the same time, encapsulating dynamically rendered code into Blade instructions can further simplify the code and improve the readability and maintainability of the code.

The above is the detailed content of How to implement permission-based display and hiding of page elements in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement permission control and user management in uniapp How to implement permission control and user management in uniapp Oct 20, 2023 am 11:15 AM

How to implement permission control and user management in uniapp

Implementing user permissions and access control using PHP and SQLite Implementing user permissions and access control using PHP and SQLite Jul 29, 2023 pm 02:33 PM

Implementing user permissions and access control using PHP and SQLite

User management and permission control in Laravel: implementing multiple users and role assignments User management and permission control in Laravel: implementing multiple users and role assignments Aug 12, 2023 pm 02:57 PM

User management and permission control in Laravel: implementing multiple users and role assignments

Best Practices for Laravel Permissions Features: How to Correctly Control User Permissions Best Practices for Laravel Permissions Features: How to Correctly Control User Permissions Nov 02, 2023 pm 12:32 PM

Best Practices for Laravel Permissions Features: How to Correctly Control User Permissions

PHP Development Guide: How to Implement Website Access Control PHP Development Guide: How to Implement Website Access Control Aug 18, 2023 pm 10:46 PM

PHP Development Guide: How to Implement Website Access Control

How to implement user login and permission control in PHP? How to implement user login and permission control in PHP? Jun 29, 2023 pm 02:28 PM

How to implement user login and permission control in PHP?

How to use ACL (Access Control List) for permission control in Zend Framework How to use ACL (Access Control List) for permission control in Zend Framework Jul 29, 2023 am 09:24 AM

How to use ACL (Access Control List) for permission control in Zend Framework

How to use permission control and authentication in C# How to use permission control and authentication in C# Oct 09, 2023 am 11:01 AM

How to use permission control and authentication in C#

See all articles