0

I want to check something in if, and if that condition is true I want to update the record that was fetched before.

$resultQuery = DB::table('cards')->where('api_id', $card->id)->first();

if (this condition will pass I want to update this record) {
    $resultQuery->update(array('price_usd' => $card->prices->usd));
}

When I use the ->update() like this, I get an error:

Call to undefined method stdClass::update();

How can I do this ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

3 Answers3

2

The first() function on laravel query builder returns a stdClass meaning Standard Class.

There is no function called update() in stdClass in php. You have called update() on stdClass, and that causes the error.

There are several ways to achieve your goal.

  1. Use Laravel query builder update() function.
$resultQuery = DB::table('cards')->where('api_id', $card->id)->first();

if (your_condition) {
    Db::table('cards')
        ->where('api_id', $card->id)
        ->update([
            'price_usd' => $card->prices->usd
        ]);
}
  1. If you don't want to fetch the card data, don't call first()
$resultQuery = DB::table('cards')->where('api_id', $card->id);

if (your_condition) {
    $resultQuery
        ->update([
             'price_usd' => $card->prices->usd
        ]);
}
  1. Use Eloquent models (Laravel's preferred way)

Create an Eloquent model for Cards (if you have not done already).

public class Card extends Model
{

}

Use eloquent query builder to fetch data. And use model update() function to update data.

$resultingCard = Card::where('api_id', $card->id)->first();

if (your_condition) {
    $resultingCard->update([
        'price_usd' => $card->prices->usd,
    ]);
}
joeybab3
  • 295
  • 2
  • 7
  • 24
Tharaka Dilshan
  • 4,371
  • 3
  • 14
  • 28
0

Something like this:

$resultQuery = DB::table('cards')->where('api_id', $card->id);

if ($resultQuery->count()) {

  $object = $resultQuery->first();
  $object->price_usd = $card->prices->usd;
  $object->save();
}

Or look for an alternative solutions here: Eloquent ->first() if ->exists()

Niels
  • 48,601
  • 4
  • 62
  • 81
0

If you're using model

You can add in card controller

$card = Card::where('api_id', $card->id)->first();

if (someConditional) 
{
  // Use card properties, number is a example.
  $card->number = 10
  // This line update this card.
  $card->save();
}

You can learn more about eloquent here.

Thiago Valente
  • 673
  • 8
  • 25