将问题重定向到Laravel中的随机ID

时间:2014-11-27 07:46:27

标签: php redirect laravel-4

在Laravel 4.2中,我有一个这样定义的路线:

Route::get('author/{id}/edit', ...);

当我尝试重定向到具有随机ID的链接(如前一个)时,它失败了:

return Redirect::to('author/{id}');
// or
return Redirect::to('author/(:any)');

但是当我手动重定向到id时,它可以成功运行,如:

return Redirect::to('author/8');
// or
return Redirect::to('author/9');

如何重定向到任何随机ID或如何使用重定向参数?

2 个答案:

答案 0 :(得分:0)

最佳做法是使用命名路由,这样您就可以始终指向命名路由。当URL更改时,您的应用程序仍将根据路由名称工作。在您的情况下,您可以使用:

Route::get('author/{id}/edit', ['as' => 'author.edit', 'uses' => 'AuthorController@edit']);

这样路线的名称是'author.edit'。

当您尝试重定向到此路线时,您可以使用 Redirect::route('author.edit', $authorId);

我对此进行了测试,它也适用于随机ID,例如:

return Redirect::route('author.edit', rand());

答案 1 :(得分:0)

如果您想重定向到随机作者页面,请尝试:

$random_id = array_rand(Author::lists('id'),1);
return Redirect::to("author/$random_id");

这假设您有一个扩展Eloquent的Author类。