在laravel中仅显示自己的帖子和管理员的所有帖子
我正在尝试显示添加到管理员的所有帖子,并且只向登录用户显示自己的帖子 这就是我在控制器中尝试的在laravel中仅显示自己的帖子和管理员的所有帖子,laravel,laravel-5.4,Laravel,Laravel 5.4,我正在尝试显示添加到管理员的所有帖子,并且只向登录用户显示自己的帖子 这就是我在控制器中尝试的 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('i
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,现在无法理解如何更改查询您可以简单地检查当前登录的用户是否是管理员,并基于此运行查询
// 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
只需检查角色并设置条件。不需要编写两次相同的查询
谢谢你的回答!嗯,这意味着我没有扮演我必须扮演的角色。如果我有角色:
admin
、author
和user
应该如何查看我的路由组?目前,我有10个权限,我附加到每个角色。我在构建这一点时有点困惑。例如,当我在登录的超级管理员中选中委托::hasRole('superadmin')
时,我看到1
,我假设它是true
,但当我更改为委托::hasRole('author')
时,我什么也看不到。。我应该再看看1
,对吗?谢谢你的回答。工作得很好。第一次处理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);
}