29

I'm trying to do something a little different and I couldn't find any way to do it. Maybe my approach is wrong but either way I figured I might find some help here.

I have a Laravel 5 project and you know how you can get the current route name by using:

\Request::route()->getName();

So I'm actually looking to do the exact opposite. Maybe not the exact opposite but what I need is to retrieve my route URL based on the name that I gave to that route. Here is my dream scenario.

my routes.php:

Route::any('/hos', "HospitalController@index")->name("hospital");

What I would like to do in my controller that I have no idea how to or even if is possible:

// I have no idea if this is possible but thats what I'm trying to accomplish
$my_route_url = \Request::route()->getURLByName("hospital");

echo $my_route_url; // this would echo: "/hos"

I might be using the wrong approach here so maybe you guys can help me out and shine some light on the issue.

Thanks!

brunomayerc
  • 295
  • 1
  • 3
  • 8

2 Answers2

55

$url = route('routeName');

if there is a param

$url = route('routeName', ['id' => 1]);

https://laravel.com/docs/5.1/helpers#method-route

David Nguyen
  • 8,368
  • 2
  • 33
  • 49
0

I guess you are trying to rename your route into a specify one In the web.php file

Route::get('anyroute', array('as' => 'newname', function() {
    $url = route('new_name');
    return "This is the $url";    
}));
Rwd
  • 34,180
  • 6
  • 64
  • 78
Yusuf Ali
  • 21
  • 2