如何在 url 中指定城市

How to specify the city in the url

有多个url

Route::get('part/{slug}', [App\Http\Controllers\PartsController::class, 'part'])->name('part');
Route::get('parts', [App\Http\Controllers\PartsController::class, 'parts'])->name('parts');
Route::get('spare-cars/{marka?}/{model?}/{slug?}', [App\Http\Controllers\CarController::class, 'spareCars'])->name('spare.cars');

我需要在每个url前面指定城市,例如

site.ru/ekaterinburg/part - 城市是动态显示的,在没有城市的情况下需要自动替换,例如

我们转到地址 site.ru/part - 重定向到城市的默认值 - site.ru/moskva/part 和其他地址类似

如何做到这一点?

回答

谢谢@shaedrich

将所有路由添加到组中,并添加了对没有城市的链接的调用处理

Route::prefix('{city?}')->group(function() {
    Route::get('part/{slug}', [App\Http\Controllers\PartsController::class, 'part'])->name('part');
    Route::get('parts', [App\Http\Controllers\PartsController::class, 'parts'])->name('parts');
    Route::get('spare-cars/{marka?}/{model?}/{slug?}', [App\Http\Controllers\CarController::class, 'spareCars'])->name('spare.cars');
    Route::get('/', [App\Http\Controllers\PartsController::class, 'checkUrl'])->name('checkUrl');
});


    public function checkUrl($slug) {
        if($slug == 'parts') {
            return redirect('moskva/parts');
        } else if($slug == 'part') {
            return redirect('moskva/part');
        }
    }

您可以使用 route group with a route prefix:

Route::prefix('{city?}')->group(function() {
    Route::get('part/{slug}', [App\Http\Controllers\PartsController::class, 'part'])->name('part');
    Route::get('parts', [App\Http\Controllers\PartsController::class, 'parts'])->name('parts');
    Route::get('spare-cars/{marka?}/{model?}/{slug?}', [App\Http\Controllers\CarController::class, 'spareCars'])->name('spare.cars');
});

如果您需要 city 参数始终存在,即使它不在 URL 中,您可以像这样将默认值传递给控制器​​操作:

class PartsController extends Controller
{
    public function part($citry = 'moskva', $slug)
    {

    }
}