Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Get URL from routes BY NAME

Tags:

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!

like image 840
brunomayerc Avatar asked Mar 02 '16 15:03

brunomayerc


People also ask

How can I get route name in Laravel?

You may use the current, currentRouteName, and currentRouteAction methods on the Route facade to access information about the route handling the incoming request: $route = Route::current(); $name = Route::currentRouteName(); $action = Route::currentRouteAction();

Which of the following is correct to get the URL of named route contact in Laravel?

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

How can you retrieve the full URL for the incoming request in Laravel?

The “path” method is used to retrieve the requested URI. The is method is used to retrieve the requested URI which matches the particular pattern specified in the argument of the method. To get the full URL, we can use the url method.

What is @param in Laravel?

The required parameters are the parameters that we pass in the URL. Sometimes you want to capture some segments of the URI then this can be done by passing the parameters to the URL. For example, you want to capture the user id from the URL.


1 Answers

$url = route('routeName');

if there is a param

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

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

like image 170
David Nguyen Avatar answered Sep 20 '22 06:09

David Nguyen