/** * Store a newly created Url in storage. * Required: long_url * Optional: custom_key, category */ public function create(Request $request) { // Get the largest Id of url from db $maxId = Url::withTrashed()->max('id'); // Validate maxId, and fix it if (!isset($maxId)) { $maxId = 0; } // Validate custom Key (key for short url), and generate new one using MAXID if (empty($request["custom_key"])) { $hashids = new Hashids('smpx', 6); $hashedUrl = $hashids->encode($maxId++); } else { $hashedUrl = $request["custom_key"]; } // trim long url (Original Url) $longUrl = trim($request["long_url"]); // Validate Long Url and send error if invalid if (strlen($longUrl) <= 0) { $error = Utility::getError(null, 400, 'Error', 'Invalid Url'); return response()->json($error, 400); } // Check whether Long url contains http protocol or not, If not then append 'http://' // Here not checking for protocols other than http if (substr($longUrl, 0, 7) !== "http://" and substr($longUrl, 0, 8) !== "https://") { $longUrl = 'http://' . $longUrl; } // Validate category if (!isset($request["category"]) || $request["category"] == '') { $category = 'no_category'; } else { $category = $request["category"]; } // build array object of Url data to save to DB $array = array('long_url' => $longUrl, 'short_url' => config('app.url') . '/' . $hashedUrl, 'is_active' => true, 'clicks' => 0, 'category' => $category); try { // save Url data to DB $urlInstance = Url::create($array); } catch (QueryException $e) { // Make logging for QueryException $error = Utility::getError(null, 400, 'Error', 'Duplicate Entry of short Url'); return response()->json($error, 400); } // Add attribute 'time' containing humna readable time format $urlInstance['time'] = $urlInstance['created_at']->diffForHumans(Carbon::now()); // Build response object $res = new \stdClass(); $res->status = 'Success'; $res->data = $urlInstance; $res->message = 'Successfully created'; // Send response Object in json string return response()->json($res, 200); }