Home  >  Article  >  PHP Framework  >  How to implement automatic allocation and recycling of permissions in Laravel

How to implement automatic allocation and recycling of permissions in Laravel

WBOY
WBOYOriginal
2023-11-04 11:03:29717browse

How to implement automatic allocation and recycling of permissions in Laravel

Laravel is a widely used PHP framework that provides convenient tools to implement common problems like permission management. In many applications, fine-grained control of users' permissions is required to ensure that they can only access what they need to access. In this article, we will explore how to automatically assign and revoke permissions in Laravel. At the same time, we will also provide specific code examples.

1. Use polymorphic association in Laravel to realize automatic allocation and recycling of permissions

Laravel's Eloquent ORM provides the function of polymorphic association, which means that we can combine multiple different models associated with the same set of data. This is very useful for automatic allocation and recycling of permissions.

For example, suppose we need to control permissions on "articles" and "comments" in our application and assign roles to users. We can create the following four models:

  • User (user)
  • Article (article)
  • Comment (comment)
  • Role (role) )

Then, we can use the polymorphic association function to associate the three models with the role:

class User extends Model
{
    public function roles()
    {
        return $this->morphToMany(Role::class, 'model', 'model_has_roles');
    }
}

class Article extends Model
{
    public function roles()
    {
        return $this->morphToMany(Role::class, 'model', 'model_has_roles');
    }
}

class Comment extends Model
{
    public function roles()
    {
        return $this->morphToMany(Role::class, 'model', 'model_has_roles');
    }
}

This example uses Laravel's polymorphic association function, so that we can Define role relationships on the three models and their records. The next step is to create an intermediate table to hold these relationships:

class CreateModelHasRolesTable extends Migration
{
    public function up()
    {
        Schema::create('model_has_roles', function (Blueprint $table) {
            $table->unsignedBigInteger('role_id');
            $table->unsignedBigInteger('model_id');
            $table->string('model_type');
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->primary(['role_id', 'model_id', 'model_type']);
        });
    }
}

Now we can associate the above model with the corresponding role. For example, assuming we assigned the "Author" role to the creator of the post, we could do this:

$article->roles()->syncWithoutDetaching([
    Role::where('name', 'author')->first()->id
]);

Similarly, create a new comment and assign the "Commenter" role to the creator of that comment, It can be implemented like this:

$comment = new Comment();
$comment->content = 'This is a new comment.';
$comment->user_id = Auth::user()->id;
$comment->save();
$comment->roles()->syncWithoutDetaching([
    Role::where('name', 'commenter')->first()->id
]);

Code like this allows us to use roles to control who can perform which actions. Now, we need a way to automatically assign the appropriate roles to new users and their posts and comments, and automatically remove the role assignments when those records are deleted.

2. Use event listeners in Laravel to realize automatic allocation and recycling of permissions

In order to realize automatic allocation and recycling of permissions, we use event listeners in the Laravel event system to capture our feelings events of interest. An event listener is a mechanism that registers application-specific event response functions. This mechanism allows us to respond to different events in the application very flexibly.

For example, Laravel provides UserCreating and UserDeleting events, which are automatically triggered when users are created and deleted. We can write an event listener to create the required role relationship when the user is created and delete this relationship when it is deleted.

First, we need to define a new event listener:

class UserEventListener
{
    public function onUserCreating(UserCreating $event)
    {
        $user = $event->user;
        $roles = Role::where('name', 'user')->get();

        foreach ($roles as $role) {
            $user->roles()->create([
                'role_id' => $role->id,
            ]);
        }
    }

    public function onUserDeleting(UserDeleting $event)
    {
        $user = $event->user;
        $user->roles()->detach();
    }
}

This event listener defines two methods. One method (onUserCreating) is automatically triggered when a user is created and assigns the "User" role to the user. Another method (onUserDeleting) automatically fires when a user deletes and deletes all records related to that role.

Next, we need to register these event listeners in our application service provider:

class AppServiceProvider extends ServiceProvider
{
    protected $listen = [
        UserCreating::class => [
            UserEventListener::class,
        ],

        UserDeleting::class => [
            UserEventListener::class,
        ],
    ];

    public function boot()
    {
        //
    }
}

Now, when we create or delete a user, the appropriate actions will be automatically performed. The final step in installing the role is to define a similar event listener for posts and comments.

class ArticleEventListener
{
    public function onArticleCreating(ArticleCreating $event)
    {
        $article = $event->article;
        $roles = Role::where('name', 'author')->get();

        foreach ($roles as $role) {
            $article->roles()->create([
                'role_id' => $role->id,
            ]);
        }
    }

    public function onArticleDeleting(ArticleDeleting $event)
    {
        $article = $event->article;
        $article->roles()->detach();
    }
}

class CommentEventListener
{
    public function onCommentCreating(CommentCreating $event)
    {
        $comment = $event->comment;
        $roles = Role::where('name', 'commenter')->get();

        foreach ($roles as $role) {
            $comment->roles()->create([
                'role_id' => $role->id,
            ]);
        }
    }

    public function onCommentDeleting(CommentDeleting $event)
    {
        $comment = $event->comment;
        $comment->roles()->detach();
    }
}

We also need to register these listeners as corresponding events in the service provider:

class AppServiceProvider extends ServiceProvider
{
    protected $listen = [
        UserCreating::class => [
            UserEventListener::class,
        ],

        UserDeleting::class => [
            UserEventListener::class,
        ],

        ArticleCreating::class => [
            ArticleEventListener::class,
        ],

        ArticleDeleting::class => [
            ArticleEventListener::class,
        ],

        CommentCreating::class => [
            CommentEventListener::class,
        ],

        CommentDeleting::class => [
            CommentEventListener::class,
        ],
    ];

    public function boot()
    {
        //
    }
}

Now, we have completed all the steps to implement automatic allocation and recycling of permissions. After this, when we create users, articles or comments, the corresponding roles will be automatically assigned. When these records are deleted, we will automatically remove them from the associated roles.

Summary:

In this article, we introduced how to automatically assign and recycle permissions in Laravel. We used polymorphic association functionality and event listeners to associate users, roles, posts, and comments together and automatically assign and recycle roles for them. At the same time, we also provide you with detailed code examples to help you better understand the method of implementing permission management in Laravel.

The above is the detailed content of How to implement automatic allocation and recycling of permissions in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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