/** * @param Model $voteable * @param int $value * @return bool */ protected static function cast(Model $voteable, $value = 1, $uuid = null) { if (!$voteable->exists || !$uuid || !Uuid::whereuuid($uuid)->first()) { return false; } $vote = static::firstOrCreate(['voteable_id' => $voteable->id, 'voteable_type' => get_class($voteable), 'uuid' => $uuid]); /** * If step_back parameter is true */ if (config('lavoter.step_back') && $vote->value != 0 && $vote->value != $value) { $vote->delete(); return true; } // Update vote value $vote->update(['value' => $value]); /** * If the given model has a vote_total column * then fill it with aggregate function sum('value') */ if (Schema::hasColumn($voteable->getTable(), 'vote_total')) { $voteable = $voteable->fresh(['votes']); $voteable->vote_total = $voteable->votes->sum('value'); $voteable->save(); } return $vote; }
/** * Check the given uuid to exists in DB * or create if the uuid isn't exists in DB. * * @param Request $request * @return Illuminate\Http\Response */ public function сheckOrCreate(Request $request) { $item = $this->uuids->firstOrCreate(['uuid' => $request->lavoter_uuid]); return response()->json(['lavoter_uuid' => $request->lavoter_uuid], 200); }