只显示自己的帖子,并在laravel中显示所有管理员帖子 [英] Display own post only and all posts for admin in laravel

查看:115
本文介绍了只显示自己的帖子,并在laravel中显示所有管理员帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示所有添加到admin的帖子,并且仅将自己的帖子显示给已记录的用户.

I'm trying to display all posts which are added to admin and only own posts to the logged user.

这就是我在控制器中尝试的操作

This is what I've trying in my controller

public function index(Request $request)
{
    $items = Item::where('author_id', Auth::user()->id)->orderBy('id','DESC')->with('author')->paginate(5);
    return view('items.index',compact('items'))
        ->with('i', ($request->input('page', 1) - 1) * 5);
}

在模型中,我有这种关系. 物品模型:

In the models I have this relations. Item model:

public function author()
{
    return $this->belongsTo(User::class);
}

用户模型

public function posts()
{
    return $this->hasMany(Item::class, 'author_id');
}  

如果已登录管理员以查看所有帖子,我该如何做?我正在使用Entrust ACL,现在不明白如何更改查询

How can I make this if admin is logged to be able to see all posts? I'm using Entrust ACL and can't understand now how to change the query

推荐答案

只需检查角色和设置条件即可.无需两次编写相同的查询.

Just check role and set condition. no need to write same query twice.

public function index(Request $request)
    {
        $query = Item::orderBy('id','DESC')->with('author');
         if(!Auth::user()->hasRole('admin')){
              $query=$query->where('author_id', Auth::user()->id);
          }
        $items = $query->paginate(5);
        return view('items.index',compact('items'))
            ->with('i', ($request->input('page', 1) - 1) * 5);
    }

这篇关于只显示自己的帖子,并在laravel中显示所有管理员帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆