1

I have relationship on User model like below:

public function brands() {
    $roles = config('constants.roles');

    if ($this->hasRole($roles['brand_site_admin'])) {
        return $this->belongsToMany(Brand::class, 'brand_has_users');
    } else 
    if ($this->hasRole($roles['client_admin'])) {
        return $this->belongsToMany(Brand::class, 'brand_has_client_admin');
    }

    // For admin role I want to return all brands, from Brand Model
    // ?? 
}

For Admin role I want to return all rows from Brand model, How can I get that? And that should be instance of BelongsToMany class, then only it won't break code in my controller.

Update:

When I do $user->brands() I want all the brands from brands table if $user is an admin (In above code if it doesn't goes in any condition then it's Admin).

Community
  • 1
  • 1
shyammakwana.me
  • 5,562
  • 2
  • 29
  • 50

1 Answers1

0

I think you should try this as suggested in this SO post, first create the relationships like this

    $roles = config('constants.roles');
public function siteAdminBrands()
    {
        return $this->hasMany(Brand::class, 'brand_has_users');
    }    

    public function clientAdminBrands()
    {
        return $this->hasMany(Brand::class, 'brand_has_client_admin');
    }

    public function brands($query)
    {
        return $query
              ->when($this->hasRole($roles['brand_site_admin']),function($q){
                  return $q->with('siteAdminBrands');
             })
             ->when($this->hasRole($roles['client_admin']),function($q){
                  return $q->with('clientAdminBrands');
             });

    }
}
Mr. Pyramid
  • 3,855
  • 5
  • 32
  • 56