Display own post only and all posts for admin in laravel

a 夏天 提交于 2020-01-25 01:01:07

问题


I'm trying to display all posts which are added to admin and only own posts to the logged user.

This is what I've trying in my controller

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

In the models I have this relations. Item model:

public function author()
{
    return $this->belongsTo(User::class);
}

User model

public function posts()
{
    return $this->hasMany(Item::class, 'author_id');
}  

How can I make this if admin is logged to be able to see all posts? I'm using Entrust ACL and can't understand now how to change the query


回答1:


Just check role and set condition. no need to write same query twice.

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



回答2:


You can simply check if the current logged in user is an admin, and based on that run a query.

// 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 returns true or false [entrust docs]



来源:https://stackoverflow.com/questions/43635051/display-own-post-only-and-all-posts-for-admin-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!