Home > Mobile >  "Incorrect integer value" when inserting data [Eloquent]
"Incorrect integer value" when inserting data [Eloquent]

Time:10-14

My controller

        $this->validate($request, [
            'master_item_id.*' => ['required'],
            'quantity.*' => ['required', 'numeric', 'gt:0']
        ]);

        $master_item_id = array_map('intval', $request->master_item_id);
        $quantity = array_map('intval', $request->quantity);
        $price = MasterItem::whereIn('id',$master_item_id)->get('price');

        $transaction = Transaction::create([
            'total_price' => 1,
            'last_edited_by' => Auth::user()->name
        ]);

        foreach ($master_item_id as $key => $no) {
            $input['transaction'] = $transaction->id;
            $input['master_item_id'] = $no;
            $input['quantity'] = $quantity[$key];
            $input['price'] = $price[$key];
            TransactionItem::create($input);
        }

My model

    protected $table = 'transaction_item';
    protected $guarded = [];
    public $timestamps = false;
    
    public function transaction()
    {
        return $this->belongsTo(Transaction::class, 'transaction_id');
    }
    public function item()
    {
        return $this->belongsTo(MasterItem::class, 'master_item_id');
    }

When I create, this error popped up.

SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '{"price":1000000}' for column `myDatabase`.`transaction_item`.`price` at row 1

I know the problem is because my $price, but I don't know how to fix this, Is there a better and easier method to fix my problem? Thanks!

CodePudding user response:

Pretty sure the problem is

$input['price'] = $price[$key];

because MasterItem::whereIn('id',$master_item_id)->get('price'); will return something like this:

[{price: X}, {price: Y} ...]

and not something like

[X, Y]

try with this:

$input['price'] = $price[$key]['price'];
  • Related