dsklzerpx64815631 2017-09-25 21: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 21: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.

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化