Friday, March 31, 2017

Override Laravel Vendor Method in Laravel 5.3

I want to add multilanguage functionality to existing laravel project. Currently I have the following route:

$user_route = function() {
  ....
}

Route::group([
  'prefix'     => ''
], $user_route 
);

Route::group([
  'prefix'     => '{language}', 
  'middleware' => 'set.lang'
], $user_route 
);

Each anchor uses route() helper from Laravel. Since I have route with 'language' prefix, I need to pass $language from every route(). There are lot of route() and I don't think updating every route to route('name', ['language' => \App::getLocale()]) is a good option. The project already have Helper class and I plan to override route() method from Illuminate\Routing\UrlGenerator with my custom method. This is what I have tried :

Functions.php

use Illuminate\Routing\UrlGenerator as Url;
....

function route($name, $parameters = [], $absolute = true)
{
  $parameters = array_add($parameters, 'language', \App::getLocale());

  $url = new Url();

  return $url->route($name, $parameters, $absolute);
}

Which obviously return error :

FatalErrorException in Functions.php line 158:

Cannot redeclare route() (previously declared in
C:\...\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php:693)

I read about Service Container but as far as my understanding, only used to manage class dependencies and performing dependency injection. How to handle this correctly? Thank you very much for your help.



via Andy

Advertisement