0

有多个网址

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');
        }
    }
4

1 回答 1

1

您可以使用带有路由前缀的路由组

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)
    {

    }
}
于 2021-07-01T15:51:44.523 回答