File app/Http/Controllers/Api/ArticleController.php
(link to Github)
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class ArticleController extends Controller
{
//
public static function upOrDownVote(User $user, $target, string $type = 'up'): bool
{
$hasVoted = $user->{'has'.ucfirst($type).'Voted'}($target);
DB::beginTransaction();
try {
$user->{$type.'Vote'}($target);
if ($hasVoted) {
$user->cancelVote($target);
foreach ($target->hubs as $hub) {
$type === 'up' ? $hub->rating-- : $hub->rating++;
$hub->save();
}
$type === 'up' ? $target->creator->rating-- : $target->creator->rating++;
$target->author->save();
DB::commit();
return false;
}
foreach ($target->hubs as $hub) {
$type === 'up' ? $hub->rating++ : $hub->rating--;
$hub->save();
}
$type === 'up' ? $target->creator->rating++ : $target->creator->rating--;
$target->author->save();
DB::commit();
} catch (Exception $e) {
DB::rollback();
abort(500);
}
return true;
}
}