2017-04-26 73 views
0

我試圖顯示所有添加到管理員的帖子,只有自己的帖子到登錄的用戶。只顯示自己的帖子和管理員在laravel的所有帖子

這是我在我的控制器

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,現在無法理解如何更改查詢

回答

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); 
    } 
+1

感謝您的回答。完美運作。第一次處理ACL的時候,我仍然有點困惑 –

1

您可以簡單地檢查當前登錄的用戶是否是管理員,並基於該查詢運行查詢。

// 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]

+0

感謝您的回答!嗯,這意味着我沒有按照自己的角色做任何事情。如果我有角色:'admin','author'和'user',我應該如何看待我的路線組?目前我有10個權限,我附加到每個角色。我在構建這個時有點困惑。 –

+0

例如當我檢查'Entrust :: hasRole('superadmin')'在superadmin中登錄時,我看到'1',我認爲它是'true',但是當我更改爲'Entrust :: hasRole('author')'I什麼也沒看見......我應該再看一遍'1',對吧? –

相關問題