Reputation: 156
I need to make a relationship between User and Subscription table. The user who registers gets a default free user and sees 1 an offer. If silver see 8 offers, gold 15, platinum 20. I made a relationship between user and subscription tables with a pivot table subscription_user. The first question is whether I made a mistake somewhere in relation the model? The second question is how to return only one offers by default, or if you subscribe to 8 offers (silver), 15 (gold), 20 (platinum) and in which controller?
User table:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('subscription')->default('free');
$table->rememberToken();
$table->timestamps();
});
Subscription table:
Schema::create('subscriptions', function (Blueprint $table) {
$table->increments('id');
$table->string('subscription');
$table->integer('offers');
$table->timestamps();
});
Sabscription_user table:
Schema::create('subscription_users', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index(); //user table
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); //foreign key relation
$table->integer('subscription_id')->unsigned()->index();
$table->foreign('subscription_id')->references('id')->on('subscriptions')->onDelete('cascade'); //foreign key relation
});
Subscription model:
class Subscription extends Model
{
public function users() {
return $this->belongsToMany('App\User');
}
}
User model:
public function subscriptions(){
return $this->belongsToMany('App\Subscription');
}
Is everything connected as it should be for many to many relationship? In which controller I can get information about offers?
Upvotes: 0
Views: 90
Reputation: 548
By convention the pivot table is named singular so you will need to specify by adding a second argument. I like to include all the arguments so there is no guessing anyway.
public function subscriptions()
{
return $this->belongsToMany("App\Subscription", 'subscription_users', 'user_id', 'subscription_id', 'id', 'id');
}
public function users()
{
return $this->belongsToMany("App\User", 'subscription_users', 'subscription_id', 'user_id', 'id', 'id');
}
Yes you should use a controller but it depends on where you are trying to display this. I imagine you will need to display the current subscriptions somewhere as well as add and remove.
Upvotes: 2