Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get primitive json request payload in Laravel 5?

Let say that this is the payload of a request:

{name : 'John', age: 42}

You can get all paramters with Request::all().

How do I get request payload correctyly if payload is a primitive type like true or 42?

Request::getContent() receives them as strings, I want them to be in correct type as well.

like image 585
zarax Avatar asked Jan 03 '17 21:01

zarax


1 Answers

You can use json_decode to decode a raw json payload to an array:

Route::post('/request', function () {
    $payLoad = json_decode(request()->getContent(), true);

    dd($payLoad['name']);
});

And you should get

John

Or can use json_decode to decode your payload from a query parameter or post data:

Route::get('/primitive', function () {
    $payLoad = json_decode(request()->get('payload'));

    dd($payLoad);
});

Hitting:

http://app.dev/primitive?payload={%20%22name%22:%20%22John%22,%20%22age%22:%2042,%20%22male%22:%20true%20}

You should get

enter image description here

like image 131
Antonio Carlos Ribeiro Avatar answered Nov 12 '22 03:11

Antonio Carlos Ribeiro