Search code examples
phplaravellaravel-routing

Checking route parameters are a specific value?


My route:

Route::get('/{type?}/{filter?}', [IndexController::class, 'index']);

Is there a way, like form requests, where I can check that $type and $filter are specific values, for example $filter is equal to new or perhaps trending?

I've considered just specifying the finite number of options as routes themselves:

Route::get('/books/new', [IndexController::class, 'index']);

But I am then unable to get these params in the controller. Please note, I do not wish to have separate controllers for each $type.


Solution

  • You can constrain the route parameter to a regular expression, as explained in the documentation.

    Route::get('/{type?}/{filter?}', [IndexController::class, 'index'])
        ->where(['filter' => '^(new|trending)$']);
    

    But I think it would make more sense to keep this logic centralised in your controller:

    public function index(string $type, string $filter)
    {
        switch ($type) {
            case "books":
                // do something
                break;
            case "films":
                // do something
                break;
            default:
                abort(404);
        }
    }