如果laravel 4中不存在特定的路由,则重定向到该页面


Redirect specific routes to page if they don't exist with laravel 4

我有一个路由,需要重定向到另一个页面,如果他们拉的数据不存在。路由为:

Route::get('{link}/{data}', 'LinkController@getLink');

其中{link}{data}是模型绑定,

Route::model('link', 'Link');
Route::model('data', 'Data');

就是这样,当这个链接的数据不存在时,它就是404,如果它存在,它就会被带到页面上。我想做的是重定向到另一个页面,如果链接否则404。我已经找到了如何在全球范围内做到这一点的建议,但我只希望它发生在这一条路由上。

任何想法?

// Link Controller
public function getLink($linkId, $dataId)
{
  if ( is_null($link) or is_null($data) ) {
    return Redirect::to('some/path');
  }
}

如果传递的模型中的任何一个在它击中你的控制器方法时为null,只需重定向它们。至于你的/{link}路线,你指的,但不显示代码,在任何闭包/控制器做类似的事情,你处理。

摆脱模型绑定-您已经离开了千篇统一的领域。

Route::get('{link}/{data?}', 'LinkController@getLink');
// note I made the data ^ parameter optional
// not sure if you want to use it like this but it's worth pointing out

在控制器中执行所有的模型检查,就像这样:

public function getLink($linkId, $dataId)
{
  $link = Link::find($linkId);
  $data = Data::find($dataId);
  if(is_null($link)){
    throw new NotFoundHttpException;// 404
  }
  elseif(is_null($data)){
    return Redirect::to('some/view');// redirect
  }
  // You could also check for both not found and handle that case differently as well.
}

很难从你的评论中确切地看出你想如何处理缺失的链接和/或数据记录,但我相信你可以从逻辑上找出答案。这个答案的要点是,你不需要使用Laravel的模型绑定,因为你可以自己做:找到记录(s)否则重定向或404.