0

I have a JSON array in an array:

{
 layouts: [
    {
      w: 6,
      h: 4,
      x: 0,
      y: 0,
      i: "n0",
      minW: 1.5,
      minH: 1,
      maxH: 1000,
      moved: false,
      static: false,
      widget: "Clock"
    },
    {
      w: 2,
      h: 2,
      x: 0,
      y: 4,
      i: "n1",
      minW: 1,
      minH: 1,
      maxH: 1000,
      moved: false,
      static: false,
      widget: "Weather"
     }
  ]
}

I need to store each widget layout in a database. When I'm trying to execute the query It returns an error that the values are empty. I tried some examples from here but they don't work for me.

function:

public function store(Request $request)
{

    $JSON = json_decode($request);

    foreach (array($JSON) as $data) {

        $i = 0;

        $w = $data[$i]['w'];
        $h = $data[$i]['h'];
        $x = $data[$i]['x'];
        $y = $data[$i]['y'];
        $i = $data[$i]['i'];
        $minW = $data[$i]['minW'];
        $minH = $data[$i]['minH'];
        $maxH = $data[$i]['maxH'];
        $moved = $data[$i]['moved'];
        $static = $data[$i]['static'];
        $type = $data[$i]['type'];

        DB::table('widgets')->insert(
            ['w' => $w,
             'h' => $h,
             'x' => $x,
             'y' => $y,
             'i' => $i,
             'minW' => $minW,
             'minH' => $minH,
             'maxH' => $maxH,
             'moved' => $moved,
             'static' => $static,
             'type_widget' => $type]
        );

        $i++;

    }

    return response()->json(201);
}

Could anyone tell me what is the correct way to loop through the data to save it?

9
  • first of all remove $i = 0; there, because that way you don't iterate through the array, move it above the foreach Commented Oct 10, 2018 at 12:11
  • I removed it but I still get the same error @sietse85 Commented Oct 10, 2018 at 12:12
  • Have you also removed all of the [$i] in $data[$i]['w'] etc? Commented Oct 10, 2018 at 12:14
  • 1
    json_decode without second parameter decodes to object, so every $data is object. Commented Oct 10, 2018 at 12:15
  • 1
    btw try json_decode($request, true) to return the data in an assoc array it will save converting each reocrd thereafter Commented Oct 10, 2018 at 12:15

3 Answers 3

3

You need to use json_decode($array, true) the second argument (true) indicates that the input string needs to be converted to an associative array, resulting in the correct parsing of your JSON.

You can also extract the JSON directly from the Request with $request->all(). I would recommend this approach as this is a lot easier and the array will always be correctly parsed. Decoding the Request object could result in a different array formatting than you originally submitted (contain data of the Request object itself in addition to your data).

Sign up to request clarification or add additional context in comments.

7 Comments

When i'm trying to use getBody() it says: Method Illuminate\Http\Request::getBody does not exist. Do I have to add something extra to the code in order to use it?
@Baspa, sorry I accidentaly used the wrong Request class from another php library I use xD. I updated my answer with the correct method
No problem thanks for updating your answer. Should I write it like this $array = $request-all() before decoding it?
@Baspa, you can do that if you prefer it for readability but it is not required :) also dont forget to add the > after - so it is like this: -> ;)
I added the code but now it says: json_decode() expects parameter 1 to be string, array given. Any idea on how to fix this?
|
1

When you succeed with Sven Hakvoorts answer, here is a shorter version of your foreach

$i = 0;
$data = json_decode($request, true);
while (isset($data['layouts'][$i])) {
    DB::table('widgets')->insert($data['layouts'][$i]);
    $i++;
}

Even shorter (and best way):

foreach ($data['layouts'] as $row) {
    DB::table('widgets')->insert($row);
}

I think you will have to rename just one column to make this short code work: type_widget to type, this way your fields and column names are equal which results in a lot shorter code as you can see.

10 Comments

Thanks for the shorter version of the foreach. I tried your code but it says: array_keys() expects parameter 1 to be array, null given. I changed type_widget to type.
You could shorten it even more to DB::table('widgets')->insert($data);
It says: ::insert() must be of the type array, null given @NigelRen
Seems like $data isn't an array but how is that possible
I think $data is just the one record of data.
|
0

1.

$JSON = json_decode($request);

change it to

$JSON = json_decode($request,true);

2. remove $i=0 from foreach loop and place it at befor foreach loop

1 Comment

when you convert it to array use simple for loop and try

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.