Skip to content
Advertisement

Sending JSON to Laravel using POST request

so I am trying to get a hang of laravel HTTP requests and am facing an error when sending a post request that contains a JSON body…

When I first tried it out, I got an error using the same code that worked for a post request that had params attached to the URL…

My store function

JavaScript

Error I got

JavaScript

I then found this post Posting JSON To Laravel

Which in turn led me to use this

JavaScript

Then I started getting this error and am not sure why…

JavaScript

EDIT

Sorry, I forgot to post the dd() output…

When I use dd($testData) I get this.

JavaScript

but when I use dd($testData->Title) I end up getting the same error

JavaScript

I am running laravel 7.0

As for my request, I am using postman.

This is the JSON am sending

JavaScript

and those are my headers and those are my headers

EDIT 2

What would I do if I’m sending a nested JSON, how would I go about trying to access the inner JSON? Nested JSON

JavaScript

Controller

JavaScript

Without adding the json()->all() I end up getting an array and when I add it I get an error, I tried converting the array using json_decode() but I couldn’t use ‘->’ to access elements in the resulting JSON I seem to be missing something here

Advertisement

Answer

The element Title of your request is empty or is not present in the request

This can be due to a typo, error in the caps or something similar.

The first error shows an error in thee database trying to insert a record with an explicit required filed with null.

The second tells you are trying to access to a property that has not being initialized.

Edit:

After reviewed the dump of your variable and your request it’s visible that you are setting your requests as an element of one array.

That is why the member Title doesn’t exists. If you try to access like this: $testData[0]->Title you will find your value.

You don’t get errors before because you are assigning the values to the main $testData object.

My suggestion is update your request like this:

JavaScript

Sending just one object instead of an array with one element.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement