skip to Main Content

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

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?

2

Answers


  1. This is comment but i have bigger text.

    In your JS hole_data accept an array

       hole_data: [{…}, {…}]
    

    On PHP inserting what is inside $request->hole_data

       $id = DB::table('holes')->insertGetId (['hole_data' => $request->hole_data]);
    

    What you get when you dd($request->hole_data) before query, is it string or array?

    Database table is holes, do you have Model Hole or Holes
    If you have Model, did you use $cast for hole_data field and what is the cast value

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