1

I'm following this tutorial which suggests a Resource Controller Laravel API Setup.

Everything is working well in a Resource Controller, I have a fair understanding as to what's going on, but when I get to the update function, I return a successful message but never update the database.

Here it is (verbatim from site):

public function update($id)
{
$url = Url::where('user_id', Auth::user()->id)->find($id);

if ( Request::get('url') )
{
    $url->url = Request::get('url');
}

if ( Request::get('description') )
{
    $url->description = Request::get('description');
}

$url->save();

return Response::json(array(
  'error' => false,
  'message' => 'url updated'),
  // or 'message' => $url),
  200
);
}

From a quick look, can you see why it's just returning what is already in the database? It doesn't even like to change the "updated_at" timestamp Laravel seems to be pretty smart about.

2 Answers2

2

I'm not 100% certain but it seems like there's a few problems with your code. I would make a few changes.

public function update($id)
{
    $url = Url::find($id);
    //Alternatively something like
    /*$url = URL::whereUserId(Auth::user()->id)->whereId($id)->first();*/

    if ( Request::has('url') )
    {
        $url->url = Request::get('url');
    }

    if ( Request::has('description') )
    {
        $url->description = Request::get('description');
    }

    $url->save();

    return Response::json(array(
        'error' => false,
        'message' => 'url updated'),
    ),
   200
    );
}
akrist
  • 351
  • 1
  • 5
  • No worries, I omitted the second question as it really doesn't pertain to this specific problem. –  Aug 19 '14 at 06:04
  • Cool, did my suggested changes make any difference? – akrist Aug 19 '14 at 06:17
  • If I remove the `if` block and hard-code a string to be passed, like `$url->url = 'asdf'` I can get it to update just fine... However, `$url->url = Request::get('url');` will just blank out the entry. –  Aug 19 '14 at 14:49
  • Instead of Request::has() and Request::get(), Try using Input::has() and Input::get(). I didn't pick up on that before but I usually wouldn't use Request for those purposes. – akrist Aug 20 '14 at 23:21
  • `Input::has()` and `get()` will also work through `curl` in the console. I've finally found my issue and it involved the encoding of the data in Postman. –  Aug 21 '14 at 03:38
1

So the problem ended up being the data format that I was sending with Postman REST Chrome Extension.

Even though I could get away with POST'ing data using the default form-data encoding, to PUT data, I had to use x-www-form-urlencoded in the options. I've found a nice resources on SO about this: application/x-www-form-urlencoded or multipart/form-data?

Community
  • 1
  • 1