major697
major697

Reputation: 1862

Laravel DB table and eloquent method updateOrCreate

    DB::table("mytable")->updateOrCreate([
      'user_id' => $user_id,
      'active' => 1,
      'created_at' => Carbon::now()
    ]);

But this code return me error:

Call to undefined method Illuminate\Database\Query\Builder::updateOrCreate()

So, according to this answer link (user stanb) I added:

protected $table = 'mytable';

And change code: DB::table($this->table)->updateOrCreate([...

But still I have this same error

Upvotes: 6

Views: 17417

Answers (2)

Omkar Frozen
Omkar Frozen

Reputation: 622

DB::table('table name')
->updateOrInsert(
    ['email' => '[email protected]', 'name' => 'Admin'],
    ['id' => '7']
);

I disagree with the other answer, we can use query builder to insert or update.

Upvotes: 25

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

It's Eloquent method, so you need to use model. Also, you need to pass two arrays as parameters:

Model::updateOrCreate([
  'user_id' => $user_id
],
[
  'active' => 1,
  'created_at' => Carbon::now()
]);

In this example, if there is a record where user_id = $user_id, the record will be updated.

Upvotes: 2

Related Questions