Laravel - 检查 $id 是否存在于 URL?
Laravel - Check if $id is exist in the URL?
如何在进一步处理之前检查 URL 中是否存在 $id?
在我的路线中:
Route::get('list', 'ListController@showList');
Route::get('list/detail/{id}', 'ListController@showListDetail');
在我的控制器文件中:
public function showListDetail($id = null)
{
if ($id == null) {
return Redirect::to("/");
}
echo "Test - Found ID: $id";
}
在浏览器中,当我输入:http://project.dev/list/detail
我得到一个错误:
Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException
但是,当我尝试 http://project.dev/list/detail/123
时它工作正常。
将您的路线更改为以下路线,这使 ID 可选:
Route::get('list/detail/{id?}', 'ListController@showListDetail');
通过像这样设置您的路线,使 id
参数成为可选参数:
Route::get('list/detail/{id?}', 'ListController@showListDetail');
有关详细信息,请参阅 route parameters 上的文档
如何在进一步处理之前检查 URL 中是否存在 $id?
在我的路线中:
Route::get('list', 'ListController@showList');
Route::get('list/detail/{id}', 'ListController@showListDetail');
在我的控制器文件中:
public function showListDetail($id = null)
{
if ($id == null) {
return Redirect::to("/");
}
echo "Test - Found ID: $id";
}
在浏览器中,当我输入:http://project.dev/list/detail
我得到一个错误:
Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException
但是,当我尝试 http://project.dev/list/detail/123
时它工作正常。
将您的路线更改为以下路线,这使 ID 可选:
Route::get('list/detail/{id?}', 'ListController@showListDetail');
通过像这样设置您的路线,使 id
参数成为可选参数:
Route::get('list/detail/{id?}', 'ListController@showListDetail');
有关详细信息,请参阅 route parameters 上的文档