CodeIgniter Forums
HOW to use PUT with ResourceController? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: HOW to use PUT with ResourceController? (/showthread.php?tid=78212)



HOW to use PUT with ResourceController? - blaasvaer - 12-15-2020

OK, this has been driving me absolutely nuts for a day now.

Can someone please explain to me HOW I could send a PUT request and have it accept an ID and DATA in json-format?

WHAT would the route look like?

WHAT would the update method look like – WHAT parameters does it need in order to JUST WORK with the "built in" update method on the Model (as is claimed in the docs)?

HOW would I SEND the data to the Model in the right format ($request->getRawInput() is of no use at all)?

I simply cannot find this information in a clear an understandable way in the docs, or online for that matter.

Code:
ROUTE: $routes->put('api/(:segment )/(:any)', 'Api::update/$1/$2');


Controller method update:


Code:
public function update ($resource = null, $id = null)
{
    $data = $this->request->getRawInput();
    $this->model->update($id, $data);
}



RE: HOW to use PUT with ResourceController? - includebeer - 12-16-2020

I just looked at the IncomingRequest class. The variable $this->body should contain the value returned by 'php://input':
PHP Code:
public function __construct($configURI $uri null$body 'php://input'UserAgent $userAgent)
{
    
// Get our body from php://input
    
if ($body === 'php://input')
    {
        
$body file_get_contents('php://input');
    }
    
$this->body      = ! empty($body) ? $body null

In my opinion, getRawInput() should return $this->body without modification, but instead it return the data using parse_str(), which I think  is a little weird:
PHP Code:
/**
 * A convenience method that grabs the raw input stream(send method in PUT, PATCH, DELETE) and decodes
 * the String into an array.
 *
 * @return mixed
 */
public function getRawInput()
{
    
parse_str($this->body$output);
    return 
$output;


In your case, getJSON() should return what you want:
PHP Code:
/**
 * A convenience method that grabs the raw input stream and decodes
 * the JSON into an array.
 *
 * If $assoc == true, then all objects in the response will be converted
 * to associative arrays.
 *
 * @param boolean $assoc   Whether to return objects as associative arrays
 * @param integer $depth   How many levels deep to decode
 * @param integer $options Bitmask of options
 *
 * @see http://php.net/manual/en/function.json-decode.php
 *
 * @return mixed
 */
public function getJSON(bool $assoc falseint $depth 512int $options 0)
{
    return 
json_decode($this->body$assoc$depth$options);


...if not, try accessing directly $this->request->body