Laravel post with content type json - php

I'm working with laravel 5 framework, i want to create a rest API and i'm getting some problems.
I have a method post that receives Json and i can't access that content, always say is [] or null
That's my controller function:
public function Register()
{
$teste = Request::json()->all();
$name=$teste['wtf'];
return $name;
}
That returns me this error "Undefined index: wtf" because the array $teste is null
How can I receive JSON properly?

From the image you showed in the comment, I realize that the data you are sending is as form-data and not JSON. Please select raw option and choose json instead of text from drop down and retry what #Moppo said

Related

How to retrieve array of objects sent by Ajax in laravel

I am using Laravel with Vuejs and AXIOS for HTTP requests. I am sending a post request with the array of objects. So in my laravel store function how can I retrieve that data from the $request?
my questions array looks like:
data:{
questions:[{
question:'',
opt1:''
},
{
question:'',
opt1:''
}
]
}
Laravel Store method in controller:
public function store(Request $request)
{
return $request;
}
vue code:
axios.post('/addTest',this.$data.questions).then(response=>{
console.log(response.data);
});
in this code questions is an array of objects.
In Laravel you have a store method and then you returning the request?Why you are doing that?To see the request from frontend? If so then I recommend you to use postman for this.
Postman is easy to use and you can send a similar request that frontend sends.Then in laravel store function you can do
dd($request) //to output the request that postman sends
You said: how can I retrieve that data from the $request
If you send from frontend something like
{ id: 1 }
Then in laravel you can do
$id = $request->get('id');
Below you can see how i send a request with postman,and how output the request.
Your request with postman
Laravel code to output request
The response from Laravel displayed in postman
If the this.$data.questions is an array, you can simply use the input() method to pull all of the questions:
$questions = $request->input();
Let say you only want to pull the question property of the second item, you can do it like so in Laravel:
$secondQuestion = $request->input('1.question');
However, it would also be nice if you pass the questions as an object:
axios.post('/addTest', { questions: this.$data.questions });
And your PHP part will look like this:
$questions = $request->input('questions');
Hope this gives you some ideas.

Laravel 5 API - Handle arrays

I am work with Laravel 5 and have implemented a working Restful API. I am trying to allow posts to be created by passing in an array like this...
post
title
excerpt
content
image
post
title
excerpt
content
image
The API currently works great for posting one individual post but how can I handle the array of posts instead?
Does anyone have an example I can see?
If you are using the Resource Controller, you should have a PostsController with a method store(). I am assuming your request payload is some JSON like this:
{"posts": [{"title":"foo"},{"title":"bar"}, …]}
So you need to json_decode the input. Then pass it to your database:
public function store()
{
$posts = json_decode($request->input('posts', ''));
if (is_array($posts)) {
DB::table('posts')->insert($posts);
}
}
There is probably some plugin or middleware or whatever to automatically decode the JSON payload. But apart from that, there is nothing special about doing what you ask for.
If you don't want to use the store() method (because it already stores a single Post or something) you can just add another route for your multiple Posts.
did you try to send JSON in the body? Here is a link with an example
Request body could look like the following:
{
"parameters":[
{
"value":{
"array":{
"elements":[
{
"string":{
"value":"value1"
}
},
{
"string":{
"value":"value2"
}
},
{
"string":{
"value":"value3"
}
}
]
}
},
"type":"Array/string",
"name":"arrayvariable"
}
]
}
This will convert the array every time you get it from the DB and every time you save it to the DB.
And here is an example using laravel casting link
Use attribute casting. Open your IdModel model and add this:
protected $casts = [
'id' => 'array' ];

Getting values sent using post method in controller in magento 2 api

I can not get values sent from post method, using http request.
I am getting values using get method, but I need to get it using post method.
I am not using any view, I want to call http url, and send some data in my controller using post method.
This is how my controller looks like,
namespace Spaarg\eMenuApi\Controller\Index;
class Products extends \Magento\Framework\App\Action\Action
{
public function __construct(\Magento\Framework\App\Action\Context $context)
{
return parent::__construct($context);
}
public function execute()
{
//$token = $this->getRequest()->getPostValue();
$token = $this->getRequest()->getPost();
}
}
I am new to magento 2, and I don't understand what is the problem.
It will be great if someone can help.
It probably has to do with the Content-type of the http request, where Magento only understands Json and Xml (this is explained here). If you're using a different Content-type in the request or your data doesn't match the type declared in the header, then getPost() will not work.
As a fallback, you can always get all the POST data by using the following way:
public function execute()
{
$postData = file_get_contents("php://input");
}
Keep in mind that this will get the raw string, so you will likely need to process it accordingly before using it (for example with json_decode() or something like that).
For more information about this, check this SO question.

Json Empty Index

I have a ionic application which sends json data to my api which uses laravel as it's backend.
When the post request is made to my route, I call a method on my controller..
This controller then takes the data and enters it into the database, however sometimes not all the data sent from the ionic application maybe there.
I.e. My laravel application is waiting for First Name, Last Name, Company and sometimes my ionic application will only send off first_name, last_name meaning the index for company is missing.
How do I in my controller check if an index exists?
See my json request:
{"data":{"first_name":"Peter","last_name":"tESt"}}
See my controller waiting the data request:
public function store(Request $request)
{
$card = NEW card;
$card->first_name = $request->data['first_name'];
$card->last_name = $request->data['last_name'];
$card->location = $request->data['location'];
$card->save();
};
In some cases the location will be included and in some cases it won't be. The application won't send a empty index either.
In PHP, you can check if a key exists in an array using array_key_exists
In your example, you could do something like:
if (array_key_exists('location', $request->data)) {
$card->location = $request->data['location'];
}

Can't get JSON input for Laravel4 POST

I am using Laravel routes to build a RESTful API. I am routing to a Controller. In it, my function "store()" (my post function) should be getting a JSON input and I'm testing it by simply returning it. I seem to be able to see the data being passed in by doing Input::get('data') but I can't do a json_decode on that. The value of the json_decode is simply null. Can anyone help me get a working example of POSTing to a route with JSON data and accessing the data?
Here's what I have:
Route
Route::post('_api/tools/itementry/items', 'ItemEntryController');
Controller
class ItemEntryController extends BaseController
{
//... other functions
public function store()
{
if(Input::has('data'))
{
$x = Input::get('data');
$data = json_decode($x);
var_dump($data);
}
}
}
I'm using a REST tester client to submit a post with the following Query string parameters:
Name: "data"
Value: { itemNumber:"test1", createdBy:"rsmith" }
This ended up being a really stupid problem. I was doing everything right, except my JSON that I was sending in the test client was formatted incorrectly. I forgot to add quotes around the key strings.
So, instead of doing { itemNumber:"test1", createdBy:"rsmith" }
I needed to do { "itemNumber":"test1", "createdBy":"rsmith" }
Now it works.

Categories