Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AbehoM's avatar

Get all through pivot table

I have three tables: User, Subscription (pivot), Plan

When an user buy a plan I add to subscription user_id and plan_id

I was wondering: how can I get all the users that has a subscription for a plan with a name vip? I wanted to do something like: Plan::ofName('vip')->users I don't know if it's possible.

Thank you.

0 likes
9 replies
wafto's avatar

Maybe creating a class named Plan that extends Illuminate\Database\Eloquent\Relations\Pivot and like any other Eloquent model create the scope query, other way might be threat the pivot table as a Model but I think that going that way maybe an id is needed on the Plan model.

mkbat's avatar

You should be able to call Plan::ofName('vip')->users; without any problem if you have a Plan belongsToMany User relationship.

Plan Model

public function users()
{
    return $this->belongsToMany('App\User');
}
mironmg's avatar

in Plan.php you need to have a relationship

public function users()
{
    return $this->belongsToMany(User::class, 'subscriptions'); //second parameter is name of the subscriptions table
}

Then in plan model you can just call the ->users() method

AbehoM's avatar

@MIRONMG - Is there a way to get the users directly in one query without the need to use first?

$vip = App/Plan::ofName('vip')->first();
$users = $vip->users;

I wanted to do something like:

$vipUsers = App/Plan::ofName('vip')->users;

Is it possible?

YeZawHein's avatar

@zfdeveloper I think User table should have one column for vip, not in Plan. So,

$plan = Plan::findOrFail($id);
$vipusers= $plan->users->where('column-name','vip')->get();
AbehoM's avatar

@YEZAWHEIN - I have a Plan table cause it won't only have "vip" but other Plans with different prices. I don't think that adding columns in the Users table for different plans is a good approach, it doesn't seem to be scalable.

mkbat's avatar
mkbat
Best Answer
Level 4

belongsToMany relationship does the job. Creating a pivot table you don't need to add anything to the user table.

Plans Table id | name | price, User Table id | username | email | ... | password

Plan Model

public function users()
{
    return $this->belongsToMany('App\User');
}

User Model

public function plan()
{
    return $this->belongsToMany('App\Plan');
}

Getting users from a specific plan. Plan Model

public function scopeGetUsers($query, string $plan_name)
{
    $plan = $query->ofName($plan_name)->first();
    if($plan)
    {
        return $plan->users;
    }
}

Then you can use it in this way.

$plan_users = Plan::getUsers('vip');

Please or to participate in this conversation.