1

I'm trying to update the stock field or create it when the model doesn't exists

The eloquent :

\App\Models\MarketingStock::updateOrCreate(
    ['marketing_id' => $attr['marketing_id']],
    ['product_id' => $attr['product_id']],
)->increment('stock',$attr['qty']);

The model :

class MarketingStock extends Model
{
    use HasFactory;

    protected $fillable = ['marketing_id','product_id','stock'];
}

The result :

SQLSTATE[HY000]: General error: 1364 Field 'stock' doesn't have a default value (SQL: insert into `marketing_stocks` (`marketing_id`, `product_id`, `updated_at`, `created_at`) values (2, 1, 2022-11-07 20:21:11, 2022-11-07 20:21:11))

I did research from these refferences : Solution 1 Solution 2

But nothing works for me How to solve this ?

owf
  • 245
  • 1
  • 9
  • 26
  • 1
    The easiest way would probably be to modify the table so that `stock` has a default value of 0. – aynber Nov 07 '22 at 13:39
  • 3
    @aynber this is not only the easiest solution but also the only solution without having to construct a custom function that resembles the updateOrCreate function. Furthermore it is also good DB-Design to default this attribute to 0. – Aless55 Nov 07 '22 at 13:53
  • is it really `qty` not `stock` ? – xenooooo Nov 07 '22 at 14:14
  • @Aless55 agreed, tahnks – owf Nov 08 '22 at 03:18

2 Answers2

1

The problem is, that you don't set the stock, while in the database the stock column isn't allowed to have a null value. So you have to change the stock column to have a default value of 0

Erik Dohmen
  • 267
  • 1
  • 6
-2

the problem is the stock field is not nullable reason why you got this error, update your field in your migration by adding nullable() to your field and it will work.

$table->integer('stock')->nullable();
Mahmoud
  • 167
  • 2
  • 7