Pra*_*eek 5 routing laravel laravel-routing laravel-route
这些是我遇到问题的路线
获取特定城市注册地点列表的路由
例如: http://localhost:8000/London , http://localhost:8000/London/Restaurants
Route::group(['namespace' => 'Page'], function() {
Route::group(['prefix' => '{city}', 'where' => ['city' => '[\w\d]+']], function() {
Route::get('/', 'CityPageController@showCityPage')->name('cityPage');
});
});
Run Code Online (Sandbox Code Playgroud)
获取特定用户个人资料及其详细信息(例如评论、照片等)的路由。
例如: http://localhost:8000/John、http://localhost:8000/John/reviews、http://localhost:8000/John/photos
Route::group(['namespace' => 'User'], function() {
Route::group(['middleware' => 'verified'], function() {
Route::group(['prefix' => '{username}', 'where' => ['username' => '[\w\d]+']], function() {
Route::get('/', 'ProfileController@showProfilePage')->name('profilePage');
Route::get('/reviews', 'ReviewController@showReviewPage')->name('reviewPage');
Route::get('/photos', 'ImageController@showPhotoPage')->name('photoPage');
});
});
});
Run Code Online (Sandbox Code Playgroud)
问题是这两条路线不能同时工作。
位于另一条路线之上的路线优先于另一条路线。
如何解决这个路由问题。
编辑
我知道有一种方法可以实现此功能,但我不知道如何实现。任何帮助表示赞赏。
小智 6
你的路由文件
Route::get('{slug1}', 'PageController@singleSlug'); # slug 1 has to be unique i.e. username and cityname
Route::get('{slug1}/{slug2}', 'PageController@doubleSlug'); # combination of slug1 and slug2 has to be unique
Run Code Online (Sandbox Code Playgroud)
控制器功能
public function singleSlug($slug1)
{
$user = User::where('name', $slug1)->first();
if ($user) {
return view('user')->compact('user');
}
$city = City::where('name', $slug1)->first();
if ($city) {
return view('city')->compact('city');
}
abort(404); # neither user nor city
}
public function doubleSlug($slug1, $slug2)
{
// check the slug2 as this value is always defined by the system
switch ($slug2) {
case 'Restaurants':
$city = City::with('restaurants')->where('name', $slug1)->first();
if ($city) {
$viewName = 'city_restos_listing';
$viewData = $city;
}
break;
case 'reviews':
$user = User::with('reviews')->where('name', $slug1)->first();
if ($user) {
$viewName = 'user_reviews_listing';
$viewData = $user;
}
break;
case 'photos':
$user = User::with('photos')->where('name', $slug1)->first();
if ($user) {
$viewName = 'user_photos_listing';
$viewData = $user;
}
break;
default:
abort(404); # the slug 2 is incorrect
break;
}
if(isset($viewName)) {
return view($viewName)->compact('viewData');
} else {
abort(404); # user or city not found
}
}
Run Code Online (Sandbox Code Playgroud)
从 Laravel 的角度来看,两个 url 是相同的:
{property}/
具有不同的属性名称city并且username没有区别,因为 laravel 不会理解伦敦是一个城市并说 Prateek 是用户名。
我建议的更好方法是在前缀前添加模型名称的标识符:EX。Route::group(['prefix' => 'users/{username}' ...而不是你的方法和城市之前的城市路线。
看看这个:https : //laravel.com/docs/6.x/controllers#resource-controllers
| 归档时间: |
|
| 查看次数: |
237 次 |
| 最近记录: |