我在web.php中有这些路线:
Route::get('/threads/create','ThreadForumController@create');
Route::get('/threads/{channel}','ThreadForumController@index');
Route::post('/threads','ThreadForumController@store');
Route::get('/threads/{channel}/{thread}','ThreadForumController@show')->name('threads.show');
Route::post('/threads/{channel}/replies','ReplyController@store');
Route::get('/threads','ThreadForumController@index');
当我进入浏览器/ thread时,我必须得到所有线程,当我去/ threads / php时我必须获得specefic线程,但我的控制器中总是有$ channel值:
public function index(Channel $channel)
{
$threads = $channel->exists() ? $channel->threads()->latest()->get() : ThreadForum::all();
return view('threads.index', compact('threads'));
}
我该如何解决?
答案 0 :(得分:3)
您可以将两条路线合并为一条:
Route::get('/threads/{channel}','ThreadForumController@index');
Route::get('/threads','ThreadForumController@index');
可以改为:
Route::get('/threads/{channel?}','ThreadForumController@index');
然后index
方法可写如下:
public function index($channel == null) {
if ($channel) {
//I always go in this way
$threads = Channel::findOrFail($channel)->threads()->latest()->get();
} else {
$threads = ThreadForum::all();
}
return view('threads.index', compact('threads'));
}
因此,您可以使用一个路线和一个方法同时服务。
答案 1 :(得分:0)
有几种方法,一种是这样的:
public function index(Channel $channel)
{
$threads = Thread::latest();
if(request('channel')) {
$threads = $channel->threads()->latest();
}
$threads = $threads->get();
return view('threads.index', compact('threads'));
}
如果您想要在路线中使用slugs('php')而不是id,则必须设置getRouteKeyName。例如,在频道模型中:
public function getRouteKeyName()
{
return 'slug';
}
public function threads()
{
return $this->hasMany(Thread::class);
}