仅显示自己的帖子和Laravel的所有帖子



我正在尝试显示所有已添加到管理员的帖子,并且仅向已记录的用户拥有帖子。

这是我在控制器中尝试的

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);
}

在模型中,我有这种关系。项目型号:

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

用户模型

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

如果登录量以查看所有帖子,我该如何做到这一点?我正在使用"委托ACL",现在不明白如何更改查询

只需检查角色和设定条件即可。无需写两次相同查询。

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);
    }

您可以简单地检查用户登录的电流是否为管理员,然后基于该查询。

// If user has 'admin' role (or any other role set in Entrust) fetch all posts, else get all posts where author_id is the same as the logged user
if(Auth::user()->hasRole('admin')) {
    $items = Item::orderBy('id','DESC')->with('author')->paginate(5);
} else {
    $items = Item::where('author_id', Auth::user()->id)->orderBy('id','DESC')->with('author')->paginate(5);
}

hasRole返回truefalse [托管文档]

最新更新