Home > OS >  Laravel increment column in updateOrCreate and get the model
Laravel increment column in updateOrCreate and get the model

Time:03-14

I am trying to increment a column and updateorcreate a record in one query by doing so:

$model = Model::updateOrCreate([
   'email' => $email
], ['received_at' => $received_at])->incremet('received_count');

This does the job as I wanted it too. It updates or create a record and increments the received_count column.

But after the query, I wanted to get the updated/created row, but when I log $model, it only logs 0 or 1. I can confirm that this is because of the ->increment().

But to be honest, I don't know any way how to increment the received_count column other than how I currently did it.

How do I achieve so that it updates or create a record, at the same time increments the received_count column, and after all of this, returns the updated/created object?

As much as posssible, I want this all in one query. Getting the model should be a memory.

CodePudding user response:

just fresh model after incremet:

  $model = Model::updateOrCreate([
            'email' => $email
        ], ['received_at' => $received_at]);
        $model->incremet('received_count');
        $model->fresh();

CodePudding user response:

$model = Model::updateOrCreate(['email' => $email], ['received_at' => $received_at]);

$model->increment('received_count');
$model->refresh(); // this will refresh all information for your model.

or you can simply:

$model = Model::updateOrCreate(['email' => $email], ['received_at' => $received_at]);
tap($model)->increment('id'); // this will return refreshed model.
  • Related