0


I have a form like this in my view:

<form action="http://localhost/RenderForm/public/handle-form" method="POST">
    <input type="hidden" name="_token" value="BOwsdSS3Zc4oI08wDutUQbvtQhGvGZXBgxaOoOFD">                                                                    
    <div class="links">
        <div>
	        First Name:<br>
	        <input name="firstName" type="text">
        </div>        
        <br>
    </div>
                                                
    <div class="links">
        <div>
	        Last Name:<br>
	        <input name="lastName" type="text">
        </div>        
        <br>
    </div>
                                                
    <div class="links">
        <div>
	        Location:<br>
	        <select name="location">
				<option value="0">HN</option>
				<option value="1">HCM</option>
			</select>
        </div>        
        <br>
    </div>
                                            
    <div>
        <button type="submit">Reset Form</button>
        <button type="submit">Complete Task</button>
    </div>
</form>

In my controller, I use $request->all() to get all form values and store into a variable. After that, I use json_encode to convert it become a Json object.
When I debug that variable, it have values:

"{"firstName":"hao","lastName":"nguyen","location":"0"}"

But what I really need is:

[ { "id" : "firstName", "value" : "hao" }, { "id" : "lastName", "value" : "nguyen" }, { "id" : "location", "value" : "0" } ]

Can you tell me how to fix this? Thank you very much!

3
  • Try $arr = [json_decode(json_encode($request->all()), true)]; Commented Apr 18, 2019 at 4:49
  • array:1 [▼ 0 => array:4 [▼ "_token" => "RKvYNS7ubX4x2AGGxSU7Rwp6ClYJnnq4TSr1ob8c" "firstName" => "hao" "lastName" => "nguyen" "location" => "0" ] ] Commented Apr 18, 2019 at 4:52
  • it's not what I need Commented Apr 18, 2019 at 4:52

1 Answer 1

1

Use foreach loop and customised all inputs like this :

$collect = []; // empty array for collect customised inputs

foreach($request->all() as $input_key => $input_value){ // split input one by one

     $collect[] = array( //customised inputs
            "id" => $input_key,
            "value" => $input_value

     );
} 

$result = json_encode($collect); //convert to json
Sign up to request clarification or add additional context in comments.

1 Comment

exactly what I need. Thank you very much! You saved my day :))

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.