2016-08-25 109 views
2

在Laravel中,我有一种方案,其中不同用户可以前往查看刀片,在其中可以看到他们创建的帖子。Laravel - 根据用户查询

在那一刻我只是传递所有的数据,但我想知道如何根据用户传递数据到视图。

例如,如果我是一个root用户我能看到一切都那么像

Post::get() 

然后

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

这将返回岗位

本质上讲我试着是一样的东西这...

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

你认为这是使用条件查询作用域可以实现的吗?

UPDATE

这是一个可怕的解决方案吗?

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

回答

0

如果您愿意,可以使用查询范围来实现。事情是这样的:

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(); 
+0

本质上来自特定部门的用户应该只能查看该部门的文章。 –

+0

请参阅我的更新答案,而不是每个部门的“if”语句,只需将部门值传递给查询即可。 – Jonathon

+0

这种感觉就像是一个更清洁的解决方案,说实话,我要去试验,但我会回来的。 –