/** * Run the database seeds. * * @return void */ public function run() { // Get Faker instance $faker = Faker\Factory::create(); // Create a number of comments for ($numComments = 0; $numComments < 25; $numComments++) { UserComment::forceCreate(['user_id' => rand(1, 15), 'comment' => $faker->sentence(rand(5, 25))]); } }
/** * Rating a comment with 0 or 1 * * @param $comment_id * @param Request $request * * @return \Illuminate\Http\Response */ public function rate($comment_id, Request $request) { /** * Things that *could* have been done here: * ======================================== * * - User authentication through a middleware to make sure only logged in users can rate. * * - ... or log unauthenticated users IP addresses and allow only 1 vote per comment and IP in 24 hours. * * - This could also be optimised to one query (simple INSERT + JOIN to make sure the comment existed, and then * count the affected rows), but I like playing with Eloquent. * * - Another approach could have been simply storing the totals for up/down votes, which would be faster, but * then wouldn't allow for any statistics or unauthenticated IP checks, if one would like to implement those. */ try { // Get comment (or throw 404) $comment = UserComment::select('comment_id')->findOrFail($comment_id); } catch (ModelNotFoundException $e) { return ResponseHelper::write(404, 1000, 'The requested comment does not exist.'); } // Get the rating $rating = $request->input('rating'); // Make sure we have a valid rating if (!in_array($rating, ['0', '1'])) { /** * - I'd usually DEBUG-level log something with e.g. Monolog. * * - One possible approach for error messages is the draft from 2014 (Api Problem): * http://tools.ietf.org/html/draft-nottingham-http-problem-07 * * - I however usually go with custom approaches, that include internal error code, readable error etc. */ return ResponseHelper::write(400, 1002, 'Invalid value given for comment rating.'); } // Create new rating for this comment $comment->ratings()->create(['rating' => $rating]); // Forward to rating() return ResponseHelper::toJson(201, $this->rating($comment_id)); }