1

I want to put json data into html form input checkbox with laravel blade.

I have multiple input checkbox values as test[],

Then I try use htmlspecialchars to print values into input.

If my frontend check this input, backend use print_r is like this

Array
(
    [0] => {"value1":"tool_ad_id","value2":"\u65e5\u4ed8"}
    [1] => {"value1":"ad_group1","value2":"\u30c4\u30fc\u30eb\u5e83\u544aID"}
)

but I use return $request->test['0']['value1']; can't get a value.

I want to get 'value1' and 'value2'.

PHP Laravel

@foreach($as as $key => $value)
      <div class="col s6 m4 l3 blue-grey lighten-5">
      <?php
            $data = ['value1' => $value['en'] ,'value2' => $value['jp'] ];
            $data_total = htmlspecialchars(json_encode($data));
       ?>
        <input type="checkbox" id="test5{{ $key }}" value="{{$data_total}}" name="test[]" />
        <label for="test5{{ $key }}">{{$value['jp']}}</label>
      </div>
@endforeach

Laravel Controller

return $request->test['0']['value1'];

Error message

Illegal string offset 'value1'

1 Answer 1

2
[0] => {"value1":"tool_ad_id","value2":"\u65e5\u4ed8"}
Index => String

PHP does not parse JSON, you are receiving the JSON as normal string. Therefore, in order to convert it to a PHP object with properties correspongind to the keys, you need to use json_decode().

Try $test = json_decode($request->test['0'], true), and then access values off the $test variable.

$value1 = $test['value1'];
$value2 = $test['value2'];
Sign up to request clarification or add additional context in comments.

2 Comments

thanks your reply~! but i want to get 'value1' and 'value2' , i try json_decode($request->test['0']['value1'], true) is also Illegal string offset 'value1'..
Do not try json_decode($request->test['0']['value1'], true) just json_decode($request->test['0'], true) and then try and access 'value1'

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.