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

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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效