4

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

2 Answers 2

6

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';
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.