Skip to content

Commit

Permalink
Make Input::json() more logical
Browse files Browse the repository at this point in the history
Now you can send JSON payloads as an actual body in a PUT or POST request, instead of only decoding a specific POST param, or whatever it was doing before.




Also, if a non-JSON mime-type is sent it will refuse to try and parse the data, instead only returning the default value. This to me seems like a much more logical usage of Input::json() than the initial implementation.
  • Loading branch information
Phil Sturgeon committed Feb 20, 2013
1 parent 075781c commit cd9fcd0
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/Illuminate/Http/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -379,15 +379,21 @@ public function replace(array $input)
/**
* Get the JSON payload for the request.
*
* @return object
* @param string $key
* @param mixed $default
* @return string
*/
public function json()
public function json($key = null, $default = null)
{
$arguments = func_get_args();
$mime = $this->retrieveItem('server', 'CONTENT_TYPE', null);

array_unshift($arguments, $this->getContent());
if (strpos($mime, '/json') === false) {
return $default;
}

$json = json_decode($this->getContent(), true);

This comment has been minimized.

Copy link
@ahuszko

ahuszko May 28, 2014

Is there any chance you make the second parameter of the json_decode() optional and changable like Request::json(null, null, false); in order to not convert the objects to array?

This comment has been minimized.

Copy link
@philsturgeon

philsturgeon May 28, 2014

This PR was done 18 months go. I have no idea if this exact code is still in use, but I would recommend you make a new PR with a change. :)


return call_user_func_array('json_decode', $arguments);
return array_get($json, $key, $default);
}

/**
Expand Down

2 comments on commit cd9fcd0

@aleemb
Copy link

@aleemb aleemb commented on cd9fcd0 Feb 27, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this return an object rather than an array?

For example, for the following request payload:

{"name":"John", "age":30}

The expected behavior should be:

$person = Input::json();
$person->name; // doesn't work
$person['name']; // works, but the request payload was never an array, it was an object

@philsturgeon
Copy link

@philsturgeon philsturgeon commented on cd9fcd0 Feb 27, 2013 via email

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.