/** * Store user rating for the article via AJAX. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function rate(Request $request) { /* * -------------------------------------------------------------------------- * Visitor gives a rating * -------------------------------------------------------------------------- * Find article that needs to be rated, find out client ip address from * request, check if the client ip gave rating to this article before, if * they did, then update their rating if they didn't then insert new. */ if ($request->ajax()) { $article = Article::findOrFail($request->input('article_id')); $ipAddress = $request->ip(); $isRated = $article->ratings()->whereIp($ipAddress)->count(); if ($isRated) { $rating = Rating::whereArticleId($request->input('article_id'))->whereIp($ipAddress)->firstOrFail(); $rating->rate = $request->input('rate'); $rating->save(); } else { $rating = new Rating(); $rating->article_id = $request->input('article_id'); $rating->ip = $ipAddress; $rating->rate = $request->input('rate'); $rating->save(); } /* * -------------------------------------------------------------------------- * Create rate article activity * -------------------------------------------------------------------------- * Create new instance of Activity and insert rate article activity. */ Activity::create(['contributor_id' => $article->contributor_id, 'activity' => Activity::giveRatingActivity($article->title, $article->slug, $request->input('rate'))]); return $article->rating()->count() == null ? 0 : $article->rating->total_rating; } else { abort(403, 'Resources are restricted.'); } }