public function vote($subName, $slug, $value) { if (!in_array($value, [-1, 0, 1])) { abort(400); } $sub = Sub::where('name', $subName)->firstOrFail(); $post = Post::where('slug', $slug)->where('sub_id', $sub->id)->firstOrFail(); try { $vote = $post->votes()->where('user_id', auth()->id())->firstOrFail(); } catch (ModelNotFoundException $e) { $vote = new Vote(); } $vote->value = $value; $vote->user()->associate(auth()->user()); $vote->voteable()->associate($post); $vote->save(); $post->score += $value; $post->save(); }