在Laravel中我有一个场景,其中不同的用户可以访问视图刀片,在那里他们可以看到他们创建的帖子。
我刚刚传递了所有数据,但我想知道如何根据用户将数据传递给视图。
例如,如果我是root用户,我会看到一切如此
Post::get()
然后
return view('someview', compact('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();
}
答案 0 :(得分: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();