Reputation: 313
I am trying to submit my form input as json format. After decoding json data into an array I can't access array.
{
"info": {
"q_title": "hello",
"q_description": "ddd",
"q_visibility": "1",
"start_date": "Thu, 05 Oct 2017 06:11:00 GMT"
}
}
This is my json data. My Laravel controller is following:
public function store_quiz(Request $request)
{
$data = json_decode($request->getContent(), true);
$input = $arrayName = array(
'title' => $data["info"]["q_title"],
);
CreateQuiz::create($input);
$redirect = '/';
return $redirect;
}
Unfortunately $data["info"]["q_title"]
returns NULL. How to access "q_tittle" of my json??
Upvotes: 7
Views: 6819
Reputation: 313
Solution:
My data was saved in var data
in jQuery.
To post data I used
$.ajax({ .... data: {data: data} .... });
instead of
$.ajax({ .... data: data .... });
So I got unexpected value from $request->getContent()
.
Upvotes: 0
Reputation: 2546
Here's a more Laravel style method of doing this:
public function store_quiz(Request $request)
{
$input = $arrayName = array(
'title' => $request->input('info.q_title'),
);
CreateQuiz::create($input);
$redirect = '/';
return $redirect;
}
And ensure your javascript app sets the Content-Type
header to application/json
. Laravel will json_decode()
it for you.
Source: https://laravel.com/docs/5.5/requests (Retrieving JSON Input Values)
Upvotes: -1
Reputation: 1290
just access your data after json_decode
like this without a second argument.
$data->info->q_title
and by using the second argument as true, which will convert your object into an array.
$data = json_decode($request->getContents(),true) //then use
$data['info']['q_title']
and if you are not getting anything in $request->getContents()
then the problem lies in the request that you are sending.
Also, check this two links for how to retrieve JSON payload
Laravel 5: Retrieve JSON array from $request
Upvotes: 5
Reputation: 5242
Maybe $request->getContent()
content is different from your example, because for me it works.
Try to check what you have in $request->getContent()
.
Example:
<?php
$source = '{
"info": {
"q_title": "hello",
"q_description": "ddd",
"q_visibility": "1",
"start_date": "Thu, 05 Oct 2017 06:11:00 GMT"
}
}';
$data = json_decode($source, true);
echo $data['info']['q_title'];
Upvotes: 1