Error: "Array to string conversion" When create multiple row data to database

  eloquent, laravel, laravel-8

I have my controller

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

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

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

        for ($i = 0; $i < count($master_item_id); $i++) {
            $data = [
                'transaction_id' => $transaction->id,
                'master_item_id' => $master_item_id,
                'quantity' => $quantity,
                'price' => $price

My view

                    <div class="form-row" id="form-clone">
                        <div class="form-group col">
                            <select name="master_item_id[]"
                                class="select2 form-control data-allow-clear="1">
                        <div class="form-group col-4">
                            <input name="quantity[]" id="quantity" type="text"
                                class="form-control" placeholder="Quantity">

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->belongsToMany(MasterItem::class, 'master_item_id');

Everytime I try to submit my create form, it just popup error Array to string conversion. I’m pretty much new to inserting multiple rows to database. How do I fix this? Or is there better way for me to create multiple rows to database

Source: Laravel

Leave a Reply