Rbex
Rbex

Reputation: 1539

Handling Scope with User Role Constraint - Laravel 5.3

If you try to look at the role name it doesn't really look good. I know this is not the best way to handle such condition. Is there a better way to do it?

 public function scopeWishlist( $query ){

     if( Auth::User()->role->name == "admin" || Auth::User()->role->name == "staff"){

        return $query->where('transaction_type', '=', 1);
    }


}

Upvotes: 0

Views: 308

Answers (1)

prateekkathal
prateekkathal

Reputation: 3582

This is a much cleaner code

public function scopeWishlist($query, $role)
{
  $roles = ['admin', 'staff'];

  return (in_array($role, $roles)) ? $query->where('transaction_type', 1) : $query;
}

Then you can do something like

Model::where('blahblah', 'blahblah')->wishlist(auth()->user()->role->name)->get();

Hope it helps :)

Upvotes: 1

Related Questions