Jason Paddle
Jason Paddle

Reputation: 1103

Display own post only and all posts for admin in laravel

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

Upvotes: 2

Views: 2527

Answers (2)

Shailesh Ladumor
Shailesh Ladumor

Reputation: 7252

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

Upvotes: 5

Leguam
Leguam

Reputation: 1212

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]

Upvotes: 1

Related Questions