Search code examples
phplaravelurilaravel-routinglaravel-7

How to URL encode a URI route parameter in Laravel


I have a URI I need to pass inside a route to a controller. How do I handle this, or more specifically, how can I pass a string that would typically need to be URL encoded first? Could this be Howhandledy, a regular expression constraint in the route?

String to pass

itm:n#_123445

Route

Route::get('getChildren/{uri}', 'ChildrenController@getChildren');

Solution

  • You can use URL facade to do that. Full path is Illuminate\Support\Facades\URL or just use \URL since it is added in config/app.php file.

    Usage:
    URL::to('/getChildren', ['itm:n#_123445']));
    
    Generated url:
    http://domain.test/getChildren/itm%3An%23_123445
    
    Handling
    Route::get('getChildren/{url}', function ($url) {
        dd($url); // itm:n#_123445
    
    });
    

    Hope this helps you