dtl85148 2016-06-08 09:54
浏览 51
已采纳

laravel 5.1中的ACL,删除用户页面中显示的每个帖子的帖子能力

I have an user page where I show all the posts by that user. This page can be accessed by other users more or less like instagram. Now the point is I want to show in every single post in that page a list for options available to the user who posted and not the other users. I checked the documentation, all the examples are on pages that show one post (my.project/post/1) let's say, so obviously that is received through a get method and in the view you can add the @can method and define the gate in the controller that spits out the post to that page. But what if I am sending all the posts to the page like this:

 public function index()
    {


        $user = Auth::user();

        $posts_with_comments = Post::with(['comments.author',

            'user' => function ($q) {

                $q->select('id', 'username');
            },

             'some_stuff'])->where('user_id', $user->id)->get()->reverse();


        return view('user.page')->with('posts',$posts_with_comments);



    }

I registered a policy like this:

class PostPolicy

{

    /**
     * @param User $user
     * @param Post $post
     * @return bool
     */
    public function deletePost(User $user, Post $post)
    {
        return $user->id === $post->user_id;

    }

in AuthServiceProvider

class AuthServiceProvider extends ServiceProvider
{


    protected $policies = [

        \App\Post::class => \App\Policies\PostPolicy::class


    ];


    /**
     * Register any application authentication / authorization services.
     *
     * @param  \Illuminate\Contracts\Auth\Access\Gate  $gate
     * @return void
     */
    public function boot(GateContract $gate)
    {
        parent::registerPolicies($gate);
    }
}

so how do I manage the gate stuff in the controller to achieve my goal?

  • 写回答

1条回答 默认 最新

  • douyouchou1085 2016-06-08 10:20
    关注

    You don't need to do anything in your controller regarding displaying this stuff. You can do it in the view. (You can go about this in other ways as well)

    @foreach ($posts as $post)
        ...
        @can('deletePost', $post)
            ... only if the user is authorized ...
        @endcan
    @endforeach
    

    For the actions though in the controller you can use the authorize method if you would like.

    public function delete($id)
    {
        $post = Post::findOrFail($id);
    
        $this->authorize('deletePost', $post);
    
        ...
    }
    

    Laravel 5.1 Docs - Authorization - Controller Authorization

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

报告相同问题?

悬赏问题

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