Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Named URL in blade template

In Django, I can do this:

<a href="{% url 'account_login' %}">Account Link</a>

which would give me domain/account/login where I have that URL named in my urls.py

url(r'^account/login/$', views.Login.as_view(), name='account_login'),

I want to do something similar in Laravel 5.2

I currently have something like this:

Route::get('/survey/new', ['as' => 'new.survey', 'uses' => 'SurveyController@new_survey']);

How do I use in my template, plus passing in parameters?

I came across this: https://laravel.com/docs/5.1/helpers, but it was just a piece of a white page without relevant content of how to actually use it.

like image 416
KhoPhi Avatar asked Aug 08 '16 20:08

KhoPhi


People also ask

How do I find my URL in blade?

To get the current URL you can call the "url()" function and then chaining it with the "current()" function which will return the current page URL. Do note that when using this method you can get the URL path value and from the result, you can determine whether to show or hide values to the user.

How can I get current page URL in Laravel?

Accessing The Current URLecho url()->current(); // Get the current URL including the query string... echo url()->full();

How does Laravel define route in blade?

All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by your application's App\Providers\RouteServiceProvider . The routes/web. php file defines routes that are for your web interface.


1 Answers

You can use the route() helper, documented here.

<a href="{{ route('new.survey') }}">My Link</a>

If you include laravelcollective/html you could use link_to_route(). This was originally part of the core but removed in Laravel 5. It's explained here

{!! link_to_route('new.survey', 'My Link') !!}

The Laravel Collective have documented the aforementioned helper here. The function prototype is as follows

link_to_route($routeName, $title = null, $parameters = [], $attributes = []);

If for example you wanted to use parameters, it accepts an array of key value pairs which correspond to the named segments in your route URI.

For example, if you had a route

Route::get('surveys/{id}', 'SurveyController@details')->name('detail.survey');

You can generate a link to this route using the following in the parameters.

['id' => $id]

A full example, echoing markup containing an anchor to the named route.

{!! link_to_route('new.survey', 'My Link', ['id' => $id]) !!}
like image 188
Ben Swinburne Avatar answered Oct 23 '22 20:10

Ben Swinburne