Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Krato/4b168ac16ba30ac616d0ca9137d1e7f6 to your computer and use it in GitHub Desktop.
Save Krato/4b168ac16ba30ac616d0ca9137d1e7f6 to your computer and use it in GitHub Desktop.
Laravel 5 - Multiple optionals parameters in route #laravel

Laravel 5 Multiple optionals parameters in route

This is an approach to get the solution of this problem: Imagine that you want to get all files inside a subdirectory and you want to show the url like: yoursite.com/files/folders/first. But you need also to go to yoursite.com/files/folders/second/inside.

How can you achieve that?

With the Laravel Regular Expression Constraint

Route::get('/files/{path?}', 'MyController@view')->where('path', '.*');

This will handle:

yoursite.com/files
yoursite.com/files/first
yoursite.com/files/folders/first
yoursite.com/files/folders/second/inside
yoursite.com/files/demo/what/im/doing

And in the controller you only need to get it like this:

public function view($path = null)
{
    dump($path);
    // Result:
    // $path = null;
    // $path = first
    // $path = folders/first
    // $path = folders/second/inside
    // $path = demo/what/im/doing
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment