我正在尝试显示添加到管理员的所有帖子,只显示已登录用户的帖子。
这就是我在控制器中尝试的内容
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');
}
如果记录管理员以便能够查看所有帖子,我该怎么做?我正在使用Entrust ACL,现在无法理解如何更改查询
答案 0 :(得分:1)
您只需检查当前登录的用户是否为管理员,并根据该用户运行查询。
// 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
返回true
或false
[entrust docs]
答案 1 :(得分:1)
只需检查角色并设置条件。无需再写两次相同的查询。
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);
}