Laravel: How to get the current url as a view helper with parameters
Asked Answered
B

1

7

I want to build a link in my view that refers to the same page like that one where its placed on. And I want to be able to give a parameter with.

For example I want to change languages. I have a route like

domain.com/{lang}/xyz

And in my view I want to do something like

<a href="{{ URL::action(this, ['lang' => 'en']) }}">EN</a>

So I can easily reload the page but just change the "lang" parameter.

Hopefully its understandable. Please try to help me.

(Another side question: Are there no ressources eg a list of all view helpers in Laravel? where do i know which viewhelpers are available?)

Bellybutton answered 11/2, 2016 at 15:17 Comment(0)
P
22

Use laravel's helper method to use in a view:

url()->current()

This will get the current URL. If you need to get the current route name,

Route::current()->getName()

Now you can use this route name to create your own new URL.

eg:

<a href="{{ URL::action(Route::currentRouteName(), ['lang' => 'en']) }}">EN</a>

Your route definition may be something like:

Route::get('/{lang}/about/', ['as'=>'about_us', 'uses'=>'PagesController@about'])

This will provide you the current URL.

But in your case, it's better to use the this package for multi language: https://github.com/mcamara/laravel-localization

It's pretty simple and easy to use.

Pocket answered 11/2, 2016 at 15:18 Comment(7)
Thats not answering my question.Bellybutton
url()->current() how should i use that inside my <a href="">EN</a> and give the {lang} parameter with it?Bellybutton
And without using php in my view? Laravel is using a template engine so you dont have to handle php code in your views. Model-View-Controller, remember? There should be a viewhelper for that.Bellybutton
Just use <a href="{{ URL::action(Route::current()->getName(), ['lang' => 'en']) }}">EN</a>Pocket
Also <a href="{{ URL::action(Route::currentRouteName(), ['lang' => 'en']) }}">EN</a>Pocket
gives me: ErrorException in UrlGenerator.php line 590: Action app\Http\Controllers\ not defined. (View: /var/www/html/app/webapp/resources/views/main.blade.php) (View: /var/www/html/app/webapp/resources/views/main.blade.php)Bellybutton
Inspect in HTML if you are getting the correct URL and try to see if you made the right route and controller methods.Pocket

© 2022 - 2024 — McMap. All rights reserved.