1

I created a REST Api. From the front i send post values with axios. (i use ReactJS). In Back with Symfony, in my Controller i want to get post values. How can i do ? I did it:

from the front:

const data = new FormData();

       let postData = {
            source: 'lcl',
            userLastname: lastname,
            userFirstname: firstname,
            text: message,
        }

data.append('data', postData);

Axios.post('http://127.0.0.1:8000/send', data)
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error)
        });

And from my back in Controller i try this:

$data = $request->request->get('data');

the value return [object Object]... How can i get the value (source, userLastname etc.).

Thank you for help.

1 Answer 1

2

you should decode your data:

$data = $request->request->get('data');

if (!empty($data)) {
    $array = json_decode($data, true); // 2nd param to get ass array
    $userLastname =  $array['userLastname']; // etc...
}

Now $array will be an array full of your JSON data. Remove the true parameter value in the json_decode() call to get a stdClass object.

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

5 Comments

Thanks for the reply. I already tried this code, unfortunately it is not work :-(
Could youprovide the result of dump($array) and the dump($data)?
That's not true. Symfony will convert the payload to an array. You don't need to decode. See my answer.
@msphn could refer me a link in the symfony doc how symony with deserilize the json object automatically
Sorry, you need github.com/symfony-bundles/json-request-bundle. Thought it’s in the default. Guess it even is depending on the skeleton

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.