/** * post - 创建短链 * @return Response */ public function store() { // 数据验证 $validator = Validator::make(Input::all(), array('url' => 'required|url'), array('url.required' => '请填写链接地址。', 'url.url' => '链接地址的格式不正确。')); if ($validator->fails()) { // 验证失败 return Redirect::action(get_class() . '@create')->withErrors($validator)->withInput(); } // 验证成功 // 查询数据库是否已存在 $record = mUrl::hasUrl(Input::get('url')); if ($record) { // 存在 return Redirect::action(get_class() . '@create')->with('shortened', $record->shortened); } // 不存在 // 生成随机短码 $shortened = mUrl::getShortened(Input::get('url')); if ($shortened) { // 成功 return Redirect::action(get_class() . '@create')->with('shortened', $shortened); } // 失败 return Redirect::action(get_class() . '@create')->with('dbError', '系统错误请稍后再试。')->withInput(); }
<?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ Route::get('/', function () { return Redirect::to('url/shortened'); }); // 短链的跳转 Route::get('{shortenedCode}', array('as' => 'urlShortenedRedirect', function ($shortenedCode) { // 根据缩短码获取完整 URL $realUrl = UrlShortenedModel::getRealUrl($shortenedCode); // 重定向 if ($realUrl) { return Redirect::to($realUrl); } App::abort(404); })); // 短链的生成 Route::group(array('prefix' => 'url/shortened'), function () { Route::get('/', 'UrlShortenedController@create'); Route::post('/', 'UrlShortenedController@store')->before('csrf|flash'); });