Example #1
0
 /**
  * Update the specified resource in storage.
  * e.g. curl -i --user a@aa.com:a1\! -H "Content-Type: application/json" -X PUT -d '{"image_url":"http://image.com/2"}' localhost:8000/api/v1/set/2
  * e.g. curl -i --user a@aa.com:a1\! -H "Content-Type: application/json" -X PUT -d '{"items":[1,2]}' localhost:8000/api/v1/set/2
  *
  * @param  int  $id
  * @return Response
  */
 public function update($id)
 {
     $validator = Validator::make(Input::all(), array('image_url' => 'url', 'items' => 'array|min:1'));
     if ($validator->fails()) {
         return Response::json(array('errors' => $validator->messages()), 400);
     }
     // Validate that all items in the items array exist
     $itemIds = Input::get('items');
     if (is_array($itemIds)) {
         if (count($itemIds) == 0) {
             return Response::json(array('errors' => "Can't have a set with no items"), 400);
         }
         $items = Item::whereIn('item_id', $itemIds)->get();
         if ($items->count() != count($itemIds)) {
             return Response::json(array('errors' => "Items don't all exist"), 400);
         }
     }
     $set = Set::find($id);
     if (!is_object($set)) {
         // Return 404 if the set we are updating does not exist
         return Response::json(null, 404);
     } else {
         if ($set->creator != Auth::user()->user_id) {
             // Return 401 Unauthorized if the set was not created by the authenticated user
             return Response::json(null, 401);
         } else {
             // Update the set's image field
             if (is_string(Input::get('image_url'))) {
                 $set->image_url = Input::get('image_url');
             }
             // Update the set's description field
             if (is_string(Input::get('description'))) {
                 $set->description = Input::get('description');
             }
             // Replace the array of items in the set
             $itemIds = Input::get('items');
             if (is_array($itemIds)) {
                 $set->items()->sync(Input::get('items'));
             }
             $set->save();
             $response = Response::json(null, 200);
             $response->header('Location', action('SetController@show', $set->set_id));
             return $response;
         }
     }
 }