Home > Back-end >  Illuminate\Database\Query\Builder::update(): Argument #1 ($values) must be of type array, stdClas
Illuminate\Database\Query\Builder::update(): Argument #1 ($values) must be of type array, stdClas

Time:12-07

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.

CodePudding user response:

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());

CodePudding user response:

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 App\Models\SubscriptionTransaction;
    $subscriptionTransactionToUpdate = SubscriptionTransaction::firstWhere('id', $currentSubscriptionTransaction->id);

    if ($subscriptionTransactionToUpdate) {
        $currentSubscriptionTransaction = new stdClass();
        $subscriptionTransactionToUpdate->update(collect($currentSubscriptionTransaction)->toArray());
    }

  • Related