Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode json data to array and access the array in PHP(Laravel)

Tags:

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??

like image 233
Md Omar Faruk Avatar asked Oct 05 '17 06:10

Md Omar Faruk


1 Answers

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

Posting JSON To Laravel

like image 114
Dhaval Purohit Avatar answered Oct 11 '22 12:10

Dhaval Purohit