I use localization functionality in my web application. But I want to add App::getLocale()
to url()
. So for example, in my view when I add <a href="{{url('/admin')}}">link</a>
I want to display the URL in HTML as http://localhost/mysite/en/admin
. How can I do it?
Can I customize built-in URL
helper function?
url() method doesn't allow that, as it generates URL for the exact value that you provide as first argument. However it's possible to achieve what you need if you switched to route() method and defined a prefix for your routes.
// define a route group with a prefix in routes.php
Route::group(['prefix' => App::getLocale()], function() {
Route::get('admin', ['as' => 'admin', 'uses' => 'AdminController@action']);
});
// generate prefixed URL
echo route('admin');
If your locale is en , then the above line should give you a URL like /en/admin
In Laravel 5.4, use the following
{{ url('Your_Prefix', 'login') }}
url just formats the whole path to the requested address, you can add whatever you want in it.
I know this is an old question, but I ran into the same problem today. Based on the other answers, I came up with the following solution: I created a helper class which uses the Laravel url()
helper function, but pre-processes the $path
variable prior to calling the helper function. I created my own implementation for both url()
and secure_url()
helper functions.
This was a post action after I implemented localization in my application, for which I consulted this question .
Take a look at my solution. I hope it is useful for someone someday:
<?php
namespace App\Http\Helpers;
class Helpers {
/**
* Generate a url for the application.
*
* @param string $path
* @param mixed $parameters
* @param bool $secure
* @return \Illuminate\Contracts\Routing\UrlGenerator|string
*/
public static function url($path = null, $parameters = [], $secure = null) {
$path = (string) $path;
if (strlen($path) > 0 && $path[0] !== '/') {
$path = '/' . $path;
}
return url(app()->getLocale() . $path, $parameters, $secure);
}
/**
* Generate a HTTPS url for the application.
*
* @param string $path
* @param mixed $parameters
* @return string
*/
public static function secure_url($path, $parameters = []) {
return static::url($path, $parameters, true);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.