dsklzerpx64815631 2017-09-25 13:08 采纳率: 100%
浏览 156
已采纳

Laravel用户更新自己帖子的权限

I'm following a tutorial on Laravel gates where users with the permission 'update-post' are allowed to edit any post in the database. In addition, any user regardless of permissions can edit posts they've submitted.

app/Providers/AuthServiceProvider.php:

Gate::define('update-post', function ($user, \App\Post $post) {
     return $user->hasAccess(['update-post']) or $user->id == $post->user_id;
});

routes/web.php:

Route::get('/edit/{post}', 'PostController@edit')
    ->name('edit_post')
    ->middleware('can:update-post,post');

Route::post('/edit/{post}', 'PostController@update')
    ->name('update_post')
    ->middleware('can:update-post,post');  

What I'm looking for is a way to add a new permission, say 'update-own-post', where only users with that permission are allowed to edit their own posts.

So, a moderator for example would have the permission 'update-post' that allows them to edit all posts. A regular user will only be able to edit their own post if they are assigned the new permission 'update-own-post' but not every user as is currently implemented.

What's the best way to go about implementing this change in my code?

  • 写回答

1条回答 默认 最新

  • douju4278 2017-09-25 13:13
    关注

    In the Gate you want to check the type of user, so they should be able to edit if one of the following are true:

    1. $user->hasAccess(['update-post'])
    2. $user->id == $post->user_id
    3. $user->isModerator()

    I don't know how you have your user types set up, but I would recommend adding a method to your user model that checks the type of user, and if the type of user is 'moderator' or whatever name you chose, it should return true.

    You would be left with something similar to:

    Gate::define('update-post', function ($user, \App\Post $post) {
        return $user->hasAccess(['update-post']) || $user->id == $post->user_id || $user->isModerator();
    });
    

    Edit -- answer from comments

    Based on your comment you can accomplish it like so, here is the cleaned up code:

    Gate::define('update-post', function ($user, \App\Post $post) { 
        return ($user->id == $post->user_id && $user->hasAccess(['update-own-post'])) || $user->hasAccess(['update-post']); 
    });
    

    The reason that this works is because your checking if {first condition} OR {second condition} meets the criteria. If the first block is true, the second block won't even be executed; however, if the first block isn't true it will then check the second to see if it is true.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部