Laravel route group with variable prefix and where condition

Viewed 721

I would like to create a route group in Laravel with a variable as a prefix. I need to set certain conditions too. How to do it properly?

I was following docs: https://laravel.com/docs/8.x/routing#route-group-prefixes but there are only general examples.

This code should create 2 routes: /{hl}/test-1 and /{hl}/test-2 where {hl} is limited to (en|pl), but it gives an error: "Call to a member function where() on null"

Route::prefix('/{hl}')->group(function ($hl) {

    Route::get('/test-1', function () {
        return 'OK-1';
    });

    Route::get('/test-2', function () {
        return 'OK-2';
    });

})->where('hl','(en|pl)');
2 Answers

The group call doesn't return anything so there is nothing to chain onto. If you make the where call before the call to group, similarly to how you are calling prefix, it will build up these attributes then when you call group it will cascade this onto the routes in the group:

Route::prefix('{hl}')->where(['h1' => '(en|pl)'])->group(function () {
    Route::get('test-1', function () {
        return 'OK-1';
    });

    Route::get('test-2', function () {
        return 'OK-2';
    });
});

By analogy with this answer:

Route::group([
    'prefix' => '{hl}',
    'where' => ['hl' => '(en|pl)']
], function ($hl) {
    Route::get('/test-1', function () {
        return 'OK-1';
    });
    Route::get('/test-2', function () {
        return 'OK-2';
    });
});

Does this solve your problem?

Related