Laravel -查询取决于用户


Laravel - query depending on user

在Laravel中,我有一个场景,在这个场景中,不同的用户可以去一个视图刀片,在那里他们可以看到他们创建的帖子。

目前我只是在传递所有的数据,但我想知道如何根据用户将数据传递给视图。

E。如果我是根用户,我可以看到所有东西,比如

Post::get()
然后

return view('someview', compact('post')

返回post

实际上我想做的是这样的…

if(user->role = their role) then you get query 1 else you get query 2

您认为使用条件查询范围可以实现这一点吗?

更新

这是个糟糕的解决方案吗?

if($user->department == "Loans")
{
    echo "you are from loans FAM";
    $articles = Article::where('department', '=', 'Loans')->get();
} 
else if($user->department == "Digital")
{
    echo "you are from digital FAM";
    $articles = Article::where('department', '=', 'Digital')->get();
} 
else if($user->department == "Consulting")
{
    echo "you are from Consulting FAM";
    $articles = Article::where('department', '=', 'Consulting')->get();
} 

如果您愿意,可以使用查询范围实现这一点。像这样:

class Post extends Model
{
    // ...
    public function scopeByUser($query, User $user)
    {
        // If the user is not an admin, show only posts they've created
        if (!$user->hasRole('admin')) {
            return $query->where('created_by', $user->id);
        }
        return $query;
    }
}

那么你可以这样使用:

$posts = Post::byUser($user)->get();

回复你的更新:

class Article extends Model
{
    // ...
    public function scopeByUser($query, User $user)
    {
        // If the user is not an admin, show articles by their department.
        // Chaining another where(column, condition) results in an AND in
        // the WHERE clause
        if (!$user->hasRole('admin')) {
            // WHERE department = X AND another_column = another_value
            return $query->where('department', $user->department)
                ->where('another_column', 'another_value');
        }
        // If the user is an admin, don't add any extra where clauses, so everything is returned.
        return $query;
    }
}

你可以像上面那样使用它。

Article::byUser($user)->get();