Update vote

@return json array
@author Risul Islam - risul321@gmail.com
434142
public function vote(Request $request)
    {
    	/* Check if user is loged in*/
    	if (!Auth::check()) {
    		return response()->json(['flag' => 0]);
    	}

    	/* Prepare data */
    	$userId = Auth::user()->id;
    	$itemId = $request->item_id;
    	$vote = $request->vote;

    	/* Get item's current like, dislike total */
    	$totalLike = TotalLike::where('item_id', $itemId)->first();

    	/* Get user's vote on this item */
		$like = Like::where(['user_id' => $userId, 'item_id' => $itemId])->first();

		/* Check if users vote on this item exists */
		if ($like != null) {
			if ($like->vote == 1) {	// if previous vote was like
				$totalLike->total_like--;	// decrease item's total like by 1
				$totalLike->total_like = $totalLike->total_like == null ? 0 : $totalLike->total_like;	// set 0 if total like is null
				if ($vote == 1) {	// if current vote is like
					$vote = 0;	// previous vote and current vote is same so discarde vote
				}
			} else if ($like->vote == -1) {	// if previous vote was dislike
				$totalLike->total_dislike--;	// decrease item's total like by 1
				$totalLike->total_dislike = $totalLike->total_dislike == null ? 0 : $totalLike->total_dislike;	// set 0 if total dislike is null
				if ($vote == -1) {	// if current vote is dislike
					$vote = 0;	// previous vote and current vote is same so discarde vote
				}
			}
		} else {
			$like = new Like;	// create new like object if previous vote not exists
		}

		/* Update vote data */
		$like->user_id = $userId;
		$like->item_id = $itemId;
		$like->vote = $vote;

		if ($vote == 1) {
			$totalLike->total_like++;	// increase total like if vote is like
		} else if ($vote == -1) {
			$totalLike->total_dislike++;	// increase total dislike if vote is dislike
		}

		$like->save();		// save like
		$totalLike->save();	//save total like,dislike

    	return response()->json(['flag' => 1, 'vote' => $vote, 'totalLike' => $totalLike->total_like, 'totalDislike' => $totalLike->total_dislike]);
    }
802488
public function getAllForInsertUpdate()
    {
        $data          = parent::getAllForInsertUpdate();
        if ($this->_from !== null) {
            $data['_from'] = $this->_from;
        }
        if ($this->_to !== null) {
            $data['_to']   = $this->_to;
        }

        return $data;
    }
316494
public function updateAccess()
    {
        $data = request()->only('role_id', 'permission_id');

        $superAdmin = Roles::superAdmin()->first();

        if( $data['role_id'] == $superAdmin->id ) {
            return \HCLog::info('ACCESS-0001', trans('HCACL::validator.roles.cant_update_super'));
        }

        if( ! auth()->user()->hasRole('admin') && ! auth()->user()->isSuperAdmin() ) {
            return \HCLog::info('ACCESS-0001', trans('HCACL::validator.roles.cant_update_roles'));
        }

        $record = RolesPermissionsConnections::where($data)->first();

        if( is_null($record) ) {
            RolesPermissionsConnections::create($data);
            $message = 'created';
        } else {
            RolesPermissionsConnections::where($data)->delete();
            $message = 'deleted';
        }

        // clear permissions and menu items cache!
        cache()->forget('hc-admin-menu');
        cache()->forget('hc-permissions');

        return ['success' => true, 'message' => $message];
    }
1178434
public function toJSON()
    {   
        $allvals = Array();
        $reflection = new \ReflectionObject($this);
        $properties = $reflection->getProperties(\ReflectionProperty::IS_PUBLIC);
        foreach($properties as $prop){
            $propkey = $prop->getName();
            $allvals[$propkey] = $this->$propkey;
        }
        $json = json_encode($allvals, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        return $json;
    }
956450
public function update()
	{
		// temporary disable relations
		$tmp_relations   = $this->relations;
		$this->relations = array();

		// Build query and execute update
		$query = \DB::update(call_user_func($this->model.'::table'));
		$tmp   = $this->build_query($query, array(), 'update');
		$query = $tmp['query'];
		$res = $query->set($this->values)->execute($this->write_connection);

		// put back any relations settings
		$this->relations = $tmp_relations;

		// Update can affect 0 rows when input types are different but outcome stays the same
		return $res >= 0;
	}
740792
private function parseUpdates()
    {
        $updates = [];

        while (true) {
            $property = [
                'selector' => null,
                'name'     => null,
                'value'    => null,
            ];

            // parse left side
            $selectorName = $this->scanner->fetchNextToken();
            $delimiter = $this->scanner->fetchNextToken();

            if ($delimiter !== '.') {
                $property['selector'] = null;
                $property['name'] = $selectorName;
                $next = $delimiter;
            } else {
                $property['selector'] = $selectorName;
                $property['name'] = $this->scanner->fetchNextToken();
                $next = $this->scanner->fetchNextToken();
            }

            // parse right side
            $property['value'] = $this->parseOperand();

            $updates[] = $property;

            $next = $this->scanner->lookupNextToken();

            if ($next == ',') {
                $next = $this->scanner->fetchNextToken();
            } elseif (strtolower($next) == 'where' || !$next) {
                break;
            }
        }

        return $updates;
    }
996485
public function getJson()
    {
        $json = array(
            'urlKeyParam' => $this->getUrlKeyParam(),
            'inputFieldName' => $this->getTokenInputName(),
            'observedCssRules' => $this->getObservedCssRules(),
            'requestUrl' => $this->getTokenUrl(),
            'cookieName' => $this->getCookieName()
        );

        return json_encode($json);
    }
35079
public function toJson()
    {
        $json = array();
        $json['id'] = $this->id;
        $json['from'] = $this->from;
        $json['color'] = $this->color;
        $json['message'] = $this->message;
        $json['notify'] = $this->notify;
        $json['message_format'] = $this->messageFormat;
        $json['date'] = $this->date;

        return $json;

    }
1016152
public function jsonSerialize()
    {
        $jsonData = [
            'identity'   => $this->identity,
            'public_key' => $this->publicKey,
            'version'    => $this->version,
            'created_at' => $this->createdAt,
        ];

        if ($this->previousCardId != null) {
            $jsonData['previous_card_id'] = $this->previousCardId;
        }

        return $jsonData;
    }
54720
public function jsonSerialize()
    {
        return [
            'author' => $this->author,
            'comment_count' => $this->comment_count,
            'comment_status' => $this->comment_status,
            'content' => $this->content,
            'created_at' => $this->created_at,
            'excerpt' => $this->excerpt,
            'format' => $this->format,
            'id' => $this->id,
            'link' => $this->link,
            'menu_order' => $this->menu_order,
            'meta' => $this->rejectHiddenMeta($this->meta),
            'mime_type' => $this->mime_type,
            'modified_at' => $this->modified_at,
            'parent_id' => $this->parent_id,
            'password' => $this->password,
            'ping' => $this->ping,
            'ping_status' => $this->ping_status,
            'pinged' => $this->pinged,
            'slug' => $this->slug,
            'status' => $this->status,
            'template' => $this->template,
            'thumbnail' => $this->thumbnail,
            'title' => $this->title,
            'type' => $this->type,
        ];
    }
424491
public function get_updates() {
		$sub_request = new DataRequestConfig($this->request);
		$version =	$this->request->get_version();
		$user = 	$this->request->get_user();

		$sub_request->parse_sql($this->select_update($this->table, $this->request->get_source(), $this->config->id['db_name'], $version, $user));
		$sub_request->set_relation(false);

		$output = $this->render_set($this->sql->select($sub_request), $this->item_class);
        
		ob_clean();
		header("Content-type:text/xml; charset=".$this->encoding);

		echo $this->updates_start();
		echo $this->get_version();
		echo $output;
		echo $this->updates_end();
	}
1117161
public function getJson()
    {
        global $CFG, $PDOX;

        $row = $PDOX->rowDie("SELECT json FROM {$CFG->dbprefix}{$this->TABLE_NAME}
                WHERE $this->PRIMARY_KEY = :PK",
            array(":PK" => $this->id));
        if ( $row === false ) return false;
        $json = $row['json'];
        if ( $json === null ) return false;
        return $json;
    }
978213
public function toJSON()
  {
    $json = json_encode( $this->toArray() );

    return str_replace(
      [
          '"%hoverCallback%"',
          '"%formatter%"',
          '"%dateFormat%"',
      ],
      [
          $this->hoverCallback,
          $this->formatter,
          $this->dateFormat,
      ],
      $json
    );
  }
460283
public function updateAction()
    {
        $this->checkAuth(AdminResources::PRODUCT, [], AccessManager::UPDATE);

        $baseForm = $this->createForm(ApiForm::PRODUCT_SALE_ELEMENTS, "form", [], [
            "validation_groups" => ["update", "Default"],
            'csrf_protection' => false,
            "cascade_validation" => true,
            "method" => "PUT",
        ]);

        $baseForm->getFormBuilder()
            ->addEventListener(
                FormEvents::PRE_SUBMIT,
                [$this, "loadProductSaleElements"],
                192
            );

        $updatedId = array();

        $con = Propel::getConnection(ProductSaleElementsTableMap::DATABASE_NAME);
        $con->beginTransaction();

        try {
            $form = $this->validateForm($baseForm);

            $entries = $form->getData();

            foreach ($entries["pse"] as $entry) {
                $this->processUpdateAction(
                    $entry,
                    $pse = ProductSaleElementsQuery::create()->findPk($entry["id"]),
                    $pse->getProduct()
                );

                $updatedId[] = $pse->getId();
            }

            $con->commit();
        } catch (\Exception $e) {
            $con->rollBack();

            return new JsonResponse(["error" => $e->getMessage()], 500);
        }

        return new JsonResponse(
            $this->getProductSaleElements(
                array_merge(
                    $this->getRequest()->query->all(),
                    [
                        "id" => implode(",", $updatedId),
                        "limit" => \count($updatedId),
                    ]
                )
            ),
            201
        );
    }
137792
public function sync()
    {
        // @todo Add support for filtering.
        $query = [
            'clientId' => $this->clientId,
            'form' => 'cjson',
            'schema' => '1.10',
        ];

        if ($this->authenticatedClient->hasAccount()) {
            $query['account'] = (string) $this->authenticatedClient->getAccount()->getMpxId();
        }

        return $this->authenticatedClient->requestAsync('GET', $this->uri, [
            'query' => $query,
        ])->then(function (ResponseInterface $response) {
            $data = \GuzzleHttp\json_decode($response->getBody(), true);

            return $data[0]['id'];
        });
    }
913698
public function actionUpdate()
	{
		$model=$this->loadModel();
		if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		if(isset($_POST['Comment']))
		{
			$model->attributes=$_POST['Comment'];
			if($model->save())
				$this->redirect(array('index'));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
779260
public function updateVote($vote)
    {

        $out = [
            "yes" => $vote->getYes(),
            "no" => $vote->getNo(),
        ];

        $this->updateValue($this->allPlayers, "VoteUpdater", Builder::getArray($out, true));
    }