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

王林
Release: 2023-11-03 08:35:19
Original
820 people have browsed it

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template