skip to Main Content

How can I convert stdClass to Array to update my DB in Laravel?

 $currentSubscriptionTransaction = new stdClass();

$subscription_transaction_to_update = DB::table('subscription_transactions')->where('id', $currentSubscriptionTransaction->id)->first();

            if (!is_null($subscription_transaction_to_update)) {
                DB::table('subscription_transactions')->where('id', $currentSubscriptionTransaction->id)->update(
                    ($currentSubscriptionTransaction)
                );
            }

I tried
array($currentSubscriptionTransaction)
but it didn’t work.

2

Answers


  1. Try this:

    $subscription_transaction_to_update = DB::table('subscription_transactions')->where('id', $currentSubscriptionTransaction->id)->first();
    
                if (!is_null($subscription_transaction_to_update)) {
                    DB::table('subscription_transactions')->where('id', $currentSubscriptionTransaction->id)->update(
                        ($currentSubscriptionTransaction->toArray()) // this has to be an array
                    );
    }
    

    A cleaner way of doing the same by using Eloquent Model

    SubscriptionTransaction::firstOrCreate($currentSubscriptionTransaction->toArray());
    
    Login or Signup to reply.
  2. humm…
    Maybe, you should better use some helper functions like collect() and toArray() ?
    see https://readouble.com/laravel/5.7/en/helpers.html if your laravel version is 5.7

    Laravel supply some useful methods or tips belong with your laravel app version.

    For example if you use a DB table , this framework has model.php like SubscriptionTransactions under Models/
    So,Can you try these code under following?

    use AppModelsSubscriptionTransaction;
        $subscriptionTransactionToUpdate = SubscriptionTransaction::firstWhere('id', $currentSubscriptionTransaction->id);
    
        if ($subscriptionTransactionToUpdate) {
            $currentSubscriptionTransaction = new stdClass();
            $subscriptionTransactionToUpdate->update(collect($currentSubscriptionTransaction)->toArray());
        }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search