Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2- How to add prefix to existing url() helper function?

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?

like image 213
Someone Avatar asked May 10 '16 12:05

Someone


People also ask

How do you add a prefix in laravel?

Route::group(['prefix'=>'admin'],function (){ Route::group(['prefix' => 'admin','middleware' => 'auth'], function () { Route::group(['prefix' => 'candidate','middleware' => 'auth'], function () { Route::get('login', 'frontend\LoginController@login'); Route::get('/home', 'DashboardController@index')->name('home');

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.

What is prefix in laravel route?

Route PrefixesThe prefix method may be used to prefix each route in the group with a given URI. For example, you may want to prefix all route URIs within the group with admin : Route::prefix('admin')->group(function () { Route::get('/users', function () { // Matches The "/admin/users" URL.

What is URL Helper in laravel?

The url helper may be used to generate arbitrary URLs for your application. The generated URL will automatically use the scheme (HTTP or HTTPS) and host from the current request being handled by the application: $post = App\Models\Post::find(1);


2 Answers

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.

like image 180
Petar-Krešimir Avatar answered Sep 17 '22 14:09

Petar-Krešimir


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

like image 40
jedrzej.kurylo Avatar answered Sep 20 '22 14:09

jedrzej.kurylo