Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rjruiz's avatar

How to store multiple data that comes in array format?

UPDATED

I made some changes to my controller and form, I still can't insert an insert associated with a tool

Within my form I have a table that allows you to dynamically add / delete input fields. In this same table I can insert as many tools as I want, I want to clarify in this same table 2 entities participate (TOOL-INSERT), with a one-to-many relationship.

When trying to save the form I receive the following error that comes from my dynamic table:

message: "Array to string conversion (SQL: insert into tools (code_tool, insert_id, position) values (www, effeee, 01))"

The doubts I have are the following: How to capture the multiple data entered in my form through my pivot table? How to store multiple data that comes in array format?

next my models, my form and my controller

model Tool:

use Illuminate\Database\Eloquent\Model;

class Tool extends Model
{
    protected $fillable = [
        'insert_id', 'position', 'code_tool', 'type', 'category', 'status', 'description', 'reason'
    ];   

    public function inserts()
    {
        return $this->hasMany(Insert::class);
    }    

    public function pieces()
    {
        return $this->belongsToMany(Piece::class)->withTimestamps();
    }
}

model Insert:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Insert extends Model
{
    protected $fillable = [
        'code_insert', 'quality', 'type', 'category', 'status', 'description', 'reason'
    ];

    public function tool()
    {
        return $this->belongsTo(Insert::class);
    } 
}

form:

<div class="row">
    {!! Form::model($piece, [
        'route' => $piece->exists ? ['admin.pieces.update', $pieces->id] : 'admin.pieces.store',   
        'method' => $piece->exists ? 'PUT' : 'POST'
    ]) !!} 

     <div class="col-md-6">    
        <div class="box box-primary">            
            <div class="box-header with-border ">
                <h3 class="box-title">Detalles del Legajo</h3>     
            </div>  
            <div class="box-body">  

            <table class="table table-striped table-bordered table-condensed table-hover" id="dynamicTable">  
                <tr>
                    <th>Posición</th>
                    <th>Herramienta</th>                 
                    <th>Inserto</th>                 
                    <th>Action</th>
                </tr>
                <tr>  
                    <td><input type="text" name="position[]" placeholder="Posicion" class="form-control select2" /></td>  
                    <td><input type="text" name="code_tool[]" placeholder="Codigo" class="form-control" /></td> 
                    <td><input type="text" name="code_insert[]" placeholder="Codigo" class="form-control" /></td>                                  
                    <td><button type="button" name="add" id="add" class="btn btn-success"><i class="fa fa-plus-square"></i> Add More</button></td>  
                </tr>  
            </table> 

            </div>
        </div>
    </div>
  {!! Form::close() !!}    
</div>

In my controller in the store method I am trying to traverse the array as follows:

controller:

public function store(Request $request)
    {
        if ($request->ajax()){
            try {
                //  Transacciones
                DB::beginTransaction();                              

                $position    = $request->position;
                $code_tool   = $request->code_tool;
                $code_insert = $request->code_insert;
                $quality     = $request->quality;                 

                for($count = 0; $count < count($position); $count++)
                {
                    $insert = array(                        
                        'code_insert' => $code_insert[$count],
                        'quality'     => $quality[$count]
                    );
                    $insert_data[] = $insert; 

                    $tool = array(
                        'position'    => $position[$count],
                        'code_tool'   => $code_tool[$count],
                        'insert_id'   => $insert_data[$count]

                    );
                    $tool_data[] = $tool;
                }

                dd($tool_data);

                Insert::insert($insert_data);
                Tool::insert($tool_data);                   


                DB::commit();

            } catch (Exception $e) {
                // anula la transacion
                DB::rollBack();
            }
        }    
    }
   

Adding a dd ($ tool_data); I inspect the console precisely in pestana network, I get the following:

array:1 [
  0 => array:3 [
    "position" => "01"
    "code_tool" => "www"
    "insert_id" => array:2 [
      "code_insert" => "effeee"
      "quality" => "de3"
    ]
  ]
]

my problem is not knowing if I am going through the array correctly since they are fields that I dynamically insert

How to capture the data from my dynamic table, traverse the array and save it correctly?

0 likes
6 replies
Cruorzy's avatar

Hey there @rjruiz i have a bit of trouble wrapping my head around your issue. But here is what I can say.

It seems like the "Tool" is 1 thing and the Insert are multiple things?

Saving a Array into the database could be done by casting it to JSON : https://laravel.com/docs/6.x/eloquent-mutators#array-and-json-casting

Also when saving a Tool you want to save the TOOL first. Then on the relationship you want to loop over the other fields and save using the relation.

$newTool->inserts()->create($data);

https://laravel.com/docs/5.7/eloquent-relationships#the-create-method

cookie_good's avatar

What Cruorzy said is spot on. I would add that using JSON datatype in MySQL ^5.7 will save a ton of effort because there are a lot of methods that work out of the box. 5.6 and earlier you have to use TEXT datatype to support JSON, and you just have to hand jam all your code. Of course, NoSQL solutions such as Mongo are more or less variants of JSON, so less fuss.

rjruiz's avatar

@cruorzy and @cookie_good I have captured and saved the data entered in my dynamic table as follows:

PieceController:

public function store(Request $request)
    {
       
        if ($request->ajax()){
            try {
                //  Transacciones
                DB::beginTransaction();              
               
                // $this->authorize('create', new Order);                               
                // dd($request->all());
                $position    = $request->position;
                $code_tool   = $request->code_tool;
                $code_insert = $request->code_insert;
                $quality     = $request->quality;                 

                for($count = 0; $count < count($position); $count++)
                {
                    $insert = array(                        
                        'code_insert' => $code_insert[$count],
                        'quality'     => $quality[$count]

                    );
                    
                    $insert = new Insert();
                    $insert->code_insert =  $code_insert[$count];
                    $insert->quality = $quality[$count];

                    if($insert->save()){
                        $tool = array(
                        'position'    => $position[$count],
                        'code_tool'   => $code_tool[$count],
                        'insert_id'   => $insert->id
                        );
                        $tool_data[] = $tool;
                    }                 
                }
                // dd($tool_data);             
              
                Tool::insert($tool_data);
                
                $gag     = Gag::create($request->all());
                $program = Program::create($request->all()); 

                $piece = $program->piece()->create([
                    'denomination' => $request['denomination'],
                    'code'         => $request['code'],
                    'time'         => $request['time'],
                    'part_piece'   => $request['part_piece'],
                    'gag_id'       => $gag->id
                ]);
                
                $piece->tools()->sync($request->get(''));
                
                DB::commit();

            } catch (Exception $e) {
                // anula la transacion
                DB::rollBack();
            }
        }    
    }

Now my problem is as follows: I need to associate the tools that I have dynamically entered into the piece, Because as I mentioned before a piece can have one or more tools associated, then how do I proceed in this case?

I mean this part of the code:

   $piece->tools()->sync($request->get(''));

but in my form I have these fields with the following names:

position[], code_tool[], code_insert[], quality[]
rjruiz's avatar

@cruorzy it's interesting what you mention: Saving a Array into the database could be done by casting it to JSON. could you suggest another example how to work with casting in json format with laravel? see other examples would be of great help to me

cookie_good's avatar

I mostly use MySQL 5.6, so I am working with tech from 10 years ago. Nevertheless, this is how I handjam it.

Turn the array in to JSON:

$json_array = json_encode($array);

$json_insert = new DataTable;
$json_insert->json_column = $json_array;
$json_insert->save();

Others probably have more current info. MySQL ^5.7 is way better as far as JSON is concerned.

PS to work with data pulled from the database, I use json_decode();

Cruorzy's avatar

I don't really use JSON to be honest. I had to do this for phone numbers, dynamically added fields.

<div class="row" v-for="(details, index) in phone_details">
                                        
    <div class="col-md-4">
        <div class="form-group">
            <input type="text" :name="'customer_phone_details[' + index + '][number]'" class="form-control" v-model="details.number" required>
        </div>
    </div>
                                            
    <div class="col-md-4">
        <div class="form-group">
            <input type="text" :name="'customer_phone_details[' + index + '][description]'" class="form-control" v-model="details.description" required>
        </div>
    </div>
</div>
<?php

public function store(Request $request)
{
    $data['customer'] = \Validator::make($request->customer, CustomerCreate::getRules())->validate();
        $data['customer_phone_details'] = \Validator::make($request->customer_phone_details,    PhoneDetailsCreate::getRules())->validate();

    \DB::beginTransaction();

    $customer = Customer::create($data['customer'], CustomerCreate::getRules());

    foreach ($data['customer_phone_details'] as $details) {
        $customer->phone_details()->create($details, PhoneDetailsCreate::getRules());
    }

    \DB::commit();
}

So for every value i got a field. 1 Customer gets created and then multiple phone_numbers gets created on relation basis. It was quite a pain for the first time to get it to work with Validations and Old data etc etc.

Also pay attention to my HTML with Vue.js Number and Description are linked to eachother so i make nested arrays to keep them together.

Please or to participate in this conversation.