我是laravel 4.1的新手,并且研究过Jeffry Way的课程
由于laravel 3和我使用4.1的解释,我的代码出错了。
Route::get('{shortened}', function($shortend)
{
// query the DB For the row with that short url
$row = Url::where('shortend', '=', $shortend)->first();
// if not found redirect to home page
if (is_null($row) ) return Redirect::to('/');
// else grab the url and redirect
return Redirect::to($row->url);
,错误是:
继续循环到主页而不是网站
这是我的完整routes.php文件
Route::get('/', function()
{
return View::make('hello');
});
Route::post('/', function()
{
$url = Input::get('url');
$record = Url::where('urls', '=', $url)->first();
if ($record) {
return View::make('result')
->with('shortend', $record->shortend);
}
// otherwise add new row and return shortned url
// create a results view and present the short url to the usr
});
Route::get('/sucess', function ()
{
return View::make('sucess');
});
Route::post('/sucess', function (){
$done = ' Great data inserted ';
$site_data = Input::get('data_insert');
$site = new Url;
$site->urls = $site_data;
$site->shortend = 'masts';
$site->save();
return $done;
});
Route::get('{shortend}', function ($shortend)
{
// query the DB For the row with that short url
$row = Url::where('shortend', '=', $shortend)->first();
// if not found redirect to home page
if (is_null($row) ) return Redirect::to('/');
// else grab the url and redirect
});
Route::get('{url}', function ($url)
{
$row = Url::where('urls', '=', $urls)->first();
return Redirect::to($row->url);
});
问题是当我返回“消息”时在else部分代码运行完美 如果我试图将其重定向到我从数据库获取的site.com之类的外部页面 我得到了循环。
我尝试为上面的网址制作一条路线,我得到的只是一个空白页。
答案 0 :(得分:0)
DB::where('shortend', $shortend)
是的缩写
DB::where('shortend', '=', $shortend)
Route::get('{path?}, ...
同时捕获'/'
并且$shortend
等于null,因此查询将返回null,因此它将再次重定向到自身。
尝试为url参数和函数使用相同的名称。
Route :: get('{slug}',function($ slug){ //你的控制器方法 }
从你的Routes文件中我创建了一个或多或少可以工作的文件:
Route::get('/', function()
{
return View::make('hello');
});
Route::post('/', function (){
$site = new Url;
$site->urls = Input::get('url');
$site->shortened = Str::random(5);
$site->save();
return View::make('success')->withSite($site);
});
Route::get('{shortened}', function ($shortened)
{
// query the DB For the row with that short url
$row = Url::where('shortened', $shortened)->first();
// if not found redirect to home page
if (is_null($row) ) return Redirect::to('/');
// else grab the url and redirect
return Redirect::to($row->url);
});