Home > Mobile >  Laravel customized subscription updating subscribed_at for all the update
Laravel customized subscription updating subscribed_at for all the update

Time:02-23

I am using a customized subscription which is not laravel's default cashier. and the migration looks as below

public function up()
{
    Schema::create('subscriptions', function (Blueprint $table) {
        $table->id();
        $table->bigInteger('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->bigInteger('plan_id')->unsigned();
        $table->foreign('plan_id')->references('id')->on('subscription_plans');
        $table->bigInteger('transaction_id')->unsigned();
        $table->foreign('transaction_id')->references('id')->on('transactions');
        $table->timestamp('subscribed_at');
        $table->timestamp('expires_at')->nullable();
        $table->boolean('is_active')->default(true);
        $table->json('benefits');
        $table->timestamps();
    });
}

and the user relation as below

// subscription
public function subscriptions(): HasMany
{
    return $this->hasMany(Subscription::class, 'user_id')->orderBy('subscribed_at', 'asc');
}

on a specific case, I update the is_active flag.

// in user model : User.php
public function createSubscription(Plan $plan): Subscription
{   
    $transaction = $this->createTransaction($plan);
    $data = [
        'plan_id' => $plan->id,
        'transaction_id' => $transaction->id,
        'is_active' => true,
        'subscribed_at' => now(),
        'expires_at' => now()->addDays($plan->validity),
        'is_active' => true,
        'benefits' => $plan->benefits
    ];
    $this->subscriptions()->update(['is_active' => false]);
    return $this->subscriptions()->create($data);
}

but it's updating all the subscribed_at timestamps. Please help me to solve this.

CodePudding user response:

Change the subscribed_at column type from timestamp to dateTime (Or make it nullable())

Like:

Schema::create('subscriptions', function (Blueprint $table) {

    // ...       
    
    $table->dateTime('subscribed_at');
    
    // ...

});
  • Related