zarax
zarax

Reputation: 831

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.

Upvotes: 12

Views: 23971

Answers (1)

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87779

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

Upvotes: 27

Related Questions