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.
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.
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.