phplaravellaravel-routingrouteparams

How to specify the city in the url


There are multiple urls

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

I need to specify the city in front of each url, for example

site.ru/ekaterinburg/part - cities are indicated dynamically, while it is necessary in the absence of a city, substitute it automatically, for example

We go to the address site.ru/part - redirect to the default value of the city - site.ru/moskva/part and similarly with other addresses

How can this be done?

Answer

Thanks @shaedrich

Added all routes to the group and added processing of calls to links without cities

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

Solution

  • You can use a 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');
    });
    

    If you need the city parameter always to be present even if it's not in the URL, you can pass a default value to the controller action like so:

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