【问题标题】:Display own post only and all posts for admin in laravel在 laravel 中只显示自己的帖子和管理员的所有帖子
【发布时间】:2017-04-26 21:23:26
【问题描述】:

我正在尝试显示添加到管理员的所有帖子,并且只向登录用户显示自己的帖子。

这就是我在控制器中尝试的方法

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,现在不明白如何更改查询

【问题讨论】:

    标签: laravel laravel-5.4


    【解决方案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);
        }
    

    【讨论】:

    • 感谢您的回答。工作完美。第一次处理 ACL,我还是有点困惑
    【解决方案2】:

    您可以简单地检查当前登录的用户是否是管理员,并在此基础上运行查询。

    // 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 [entrust docs]

    【讨论】:

    • 感谢您的回答!嗯,这意味着我没有按照应有的方式扮演我的角色。如果我有角色:adminauthoruser 应该如何查看我的路线组?目前,我有 10 个权限附加到每个角色。我在构建这个时有点困惑。
    • 例如,当我检查Entrust::hasRole('superadmin') 登录超级管理员时,我看到1,我假设它是true,但是当我更改为Entrust::hasRole('author') 时,我什么也看不到.. 我应该再次看到@ 987654333@,对吧?
    猜你喜欢
    • 2020-11-18
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 2019-12-29
    • 2011-06-22
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多