Match Wildcard Routes in Laravel

July 18th, 2024 • 1 minute read time

Here's a quick tip on matching wildcard routes in Laravel. Once you're done, you can access the wildcard value and do anything you need to do with it.

To define the route, give it a placeholder name. In this case, I've called it any, but... any name will do.

Route::get('/{any}', function (string $path) {
    dd($path);
})
->where('any', '.*');

In the code above, we're chaining on where. Give the placeholder's name here (any in this case) and use the .* regular expression to match it.

As an example, if we access the URL as mysite.test/some/deep/path, you'll see the following dumped out:

/some/deep/path

This technique is useful for creating nested category lookups, but once you've matched a wildcard route, you can assess the value and do anything you need!

If you found this article helpful, you'll love our practical screencasts.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first!

Tagged under