Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel update data that is an array works while insert does not

Using Laravel 9, Im able to UPDATE an empty field hole_data by posting an array of objects:

JS:

data = {
   id:1,
   name:'A Name',
   hole_data: [{…}, {…}]
}

await axiosClient.post('/updateholedata', data);

Laravel/PHP

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public function updateHoleData(Request $request) {
   DB::table('holes')
   ->where('id', $request->id)
   ->update(['hole_data' => $request->hole_data]);              
   return $this->index();
}

But when i do an INSERT (data same as above without ID) I get an "Array to string conversion" error on hole_data:

JS:

await axiosClient.post('/addholedata', data);

Laravel/PHP:

public function addHoleData(Request $request) {
   $id = DB::table('holes')->insertGetId (['hole_data' => $request->hole_data]);
   return $id;
}

And the unusual thing that’s making my head scratch is that i can INSERT the name then get the ID and then UPDATE the hole_data using the ID.

public function addHoleData(Request $request) {
   $id = DB::table('holes')->insertGetId (['name' => $request->name]); //Insert to get ID

   DB::table('holes')
   ->where('id', $id) //use id to insert hole_data
   ->update(['hole_data' => $request->hole_data])
}

Why am i getting an error on just inserting when i can insert then update on the same data from the request?

>Solution :

On Insert try to json_encode() the hole_data if it is not a string

As MySQL will not allows complicated data structures (like array of objects) you can json_encode and store it as a string

['hole_data' => json_encode($request->hole_data)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading