skip to Main Content

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

The eloquent :

AppModelsMarketingStock::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 ?

2

Answers


  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

    Login or Signup to reply.
  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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search