szainmehdi's avatar

Eloquent model relationship, but without constraints?

This may seem like an odd request, but I can't think of any other way to put it.

My application has a many-to-many relationship between users and "accounts". A single account can have many users, and a single user can access multiple accounts.

So I have admin users in my app that should have access to all current and future accounts. My idea was to create an eloquent relationship that works like HasMany or BelongsTo, but without that where clause that limits results.

public function accounts()
{
    if($this->hasRole(Role::ADMIN)) {
        return $this->hasAll(Account::class);
    }
    return $this->belongsToMany(Account::class);
}

// That way, in the application...
$user->hasRole(Role::ADMIN); // => true
$user->accounts; // => all accounts in my database

$user->hasRole(Role::ADMIN); // => false
$user->accounts; // => only assigned accounts

Is something like this possible?

0 likes
6 replies
RemiC's avatar

Is there any reason for not simply returning Accounts::all() ?

experiencedguy's avatar

@REMIC - You can´t, since (at least for a authentification model) you will have to return a relationship.

Snapey's avatar

@1000ml the OP is possibly no longer a developer since he posted this 8 YEARS AGO

Besides, its not even a problem, just not understanding authorization.

2 likes
1000ml's avatar

@Snapey LOL. what kind of problem do you have with old threads? Have you heard about Google Search? And what kind of strange problem do you have to spend your time giving this kind of replies to gain some ranking points or XPs on Laracasts? I hope a mod chimes in.

Besides, I'm not sure you understood that there's more behind OPs question. It seems naive but it's not. And authorization has nothing to do with it.

Snapey's avatar

@1000ml If you feel that the original question is more nuanced, and therefore your own situation is as well, then start your own question and we will be sure to give it due care and attention.

But, to expect someone to remember from 8 years ago in a framework version that is many, many versions old is probably not realistic.

btw, I have more than enough XP thanks

btw, there are no official mods, so this is me chiming in

Please or to participate in this conversation.