{"_id":"570dfac85ff0f032005d1dc5","project":"563b65bd9e3f2225009fd2bc","user":"570df764b22f0129008dfc23","__v":18,"category":{"_id":"563b6b25e951f60d000b4513","version":"563b65bd9e3f2225009fd2bf","__v":6,"pages":["563c21fd19ae7b0d0050d45b","563c220c7539dd0d00dbee87","563c2218ac77910d00279fe7","563c2233d8f2d20d00448b4f","563c2376913e650d00b65dbd","563c907319ae7b0d0050d528"],"project":"563b65bd9e3f2225009fd2bc","sync":{"url":"","isSync":false},"reference":false,"createdAt":"2015-11-05T14:43:49.565Z","from_sync":false,"order":1,"slug":"the-basics","title":"The Basics"},"parentDoc":null,"version":{"_id":"563b65bd9e3f2225009fd2bf","project":"563b65bd9e3f2225009fd2bc","__v":4,"createdAt":"2015-11-05T14:20:45.639Z","releaseDate":"2015-11-05T14:20:45.639Z","categories":["563b65be9e3f2225009fd2c0","563b6b25e951f60d000b4513","563c239e260dde0d00c5e890","563c2440260dde0d00c5e891"],"is_deprecated":false,"is_hidden":false,"is_beta":true,"is_stable":true,"codename":"","version_clean":"4.0.0","version":"4.0"},"updates":[],"next":{"pages":[],"description":""},"createdAt":"2016-04-13T07:52:40.085Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":9,"body":".\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"USAGE\"\n}\n[/block]\nLaravel Localization uses the URL given for the request. \n\nIn order to achieve this purpose, a route group should be added into the ***routes.php*** file. It will filter all pages that must be localized.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  // app/Http/routes.php\\n\\n    Route::group(['prefix' => LaravelLocalization::setLocale()], function()\\n    {\\n        /** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/\\n        Route::get('/', function()\\n        {\\n            return View::make('hello');\\n        });\\n\\n        Route::get('test',function(){\\n            return View::make('test');\\n        });\\n    });\\n\\n    /** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nOnce this route group is added to the routes file, a user can access all locales added into ***supportedLocales*** ('en' and 'es' by default, look at the config section to change that option). For example, a user can now access two different locales, using the following addresses:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"    http://url-to-laravel/en\\n    http://url-to-laravel/es\\n    http://url-to-laravel\",\n      \"language\": \"text\"\n    }\n  ]\n}\n[/block]\nIf the locale is not present in the url or it is not defined in ***supportedLocales***, the system will use the application default locale or the user's browser default locale (if defined in config file).\n\nOnce the locale is defined, the locale variable will be stored in a session (if the middleware is enabled), so it is not necessary to write the /lang/ section in the url after defining it once, using the last known locale for the user. \n\nIf the user accesses to a different locale this session value would be changed, translating any other page he visits with the last chosen locale.\n\nTemplate files and all locale files should follow the Lang class.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"MIDDLEWARE\"\n}\n[/block]\nMoreover, this package includes a middleware object to redirect all \"non-localized\" routes to the corresponding \"localized\".\n\nIf a user navigates to http://url-to-laravel/test and the system has this middleware active and 'en' as the current locale for this user, it would redirect (301) him automatically to http://url-to-laravel/en/test. This is mainly used to avoid duplicate content and improve SEO performance.\n\nYou have to register the middleware in the ***app/Http/Kernel.php*** file like this:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"   <?php namespace App\\\\Http;\\n\\n    use Illuminate\\\\Foundation\\\\Http\\\\Kernel as HttpKernel;\\n\\n    class Kernel extends HttpKernel {\\n        /**\\n         * The application's route middleware.\\n         *\\n         * :::at:::var array\\n         */\\n        protected $routeMiddleware = [\\n            /**** OTHER MIDDLEWARE ****/\\n            'localize' => \\\\Mcamara\\\\LaravelLocalization\\\\Middleware\\\\LaravelLocalizationRoutes::class,\\n            'localizationRedirect' => \\\\Mcamara\\\\LaravelLocalization\\\\Middleware\\\\LaravelLocalizationRedirectFilter::class,\\n            'localeSessionRedirect' => \\\\Mcamara\\\\LaravelLocalization\\\\Middleware\\\\LocaleSessionRedirect::class\\n            // REDIRECTION MIDDLEWARE\\n        ];\\n\\n    }\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php \\n..\\n// app/Http/routes.php\\n\\n    Route::group(\\n    [\\n        'prefix' => LaravelLocalization::setLocale(),\\n        'middleware' => [ 'localeSessionRedirect', 'localizationRedirect' ]\\n    ],\\n    function()\\n    {\\n        /** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/\\n        Route::get('/', function()\\n        {\\n            return View::make('hello');\\n        });\\n\\n        Route::get('test',function(){\\n            return View::make('test');\\n        });\\n    });\\n\\n    /** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nIn order to activate it, you just have to attach this middleware to the routes you want to be accessible localized.\n\nIf you want to hide the default locale but always show other locales in the url, switch the ***hideDefaultLocaleInURL*** config value to true. Once it's true, if the default locale is en (english) all URLs containing /en/ would be redirected to the same url without this fragment '/' but maintaining the locale as en (English).\n\n**IMPORTANT** - When ***hideDefaultLocaleInURL*** is set to true, the unlocalized root is treated as the applications default locale ***app.locale***. Because of this language negotiation using the Accept-Language header will NEVER occur when ***hideDefaultLocaleInURL*** is true.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"HELPERS\"\n}\n[/block]\nThis package comes with some useful functions, like:\n\n## **Get URL for an specific locale**\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"   <?php\\n\\t\\t \\n\\t\\t /**\\n     * Returns an URL adapted to $locale\\n     *\\n     * @param  string|boolean   $locale     Locale to adapt, false to remove locale\\n     * @param  string|false     $url        URL to adapt in the current language. If not passed, the current url would be taken.\\n     * @param  array            $attributes Attributes to add to the route, if empty, the system would try to extract them from the url.\\n     *\\n     * @throws UnsupportedLocaleException\\n     *\\n     * @return string|false             URL translated, False if url does not exist\\n     */\\n    public function getLocalizedURL($locale = null, $url = null, $attributes = array())\\n\\n    //Should be called in a view like this:\\n    {{ LaravelLocalization::getLocalizedURL(optional string $locale, optional string $url, optional array $attributes) }}\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nIt returns a URL localized to the desired locale.\n\n## **Get Clean routes**\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php\\n\\n\\t   /**\\n     * It returns an URL without locale (if it has it)\\n     * Convenience function wrapping getLocalizedURL(false)\\n     *\\n     * @param  string|false     $url      URL to clean, if false, current url would be taken\\n     *\\n     * @return string          URL with no locale in path\\n     */\\n    public function getNonLocalizedURL($url = null)\\n\\n    //Should be called in a view like this:\\n    {{ LaravelLocalization::getNonLocalizedURL(optional string $url) }}\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nIt returns a URL clean of any localization.\n\n## **Get URL for an specific translation key** \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php\\n\\n\\t\\t/**\\n     * Returns an URL adapted to the route name and the locale given\\n     *\\n     * @throws UnsupportedLocaleException\\n     *\\n     * @param  string|boolean   $locale             Locale to adapt\\n     * @param  string           $transKeyName       Translation key name of the url to adapt\\n     * @param  array            $attributes         Attributes for the route (only needed if transKeyName needs them)\\n     *\\n     * @return string|false     URL translated\\n     */\\n    public function getURLFromRouteNameTranslated($locale, $transKeyName, $attributes = array())\\n\\n    //Should be called in a view like this:\\n    {{ LaravelLocalization::getURLFromRouteNameTranslated(string $locale, optional array $transKeyNames, optional array $attributes) }}\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nIt returns a route, localized to the desired locale using the locale passed. If the translation key does not exist in the locale given, this function will return false.\n\n## **Get Supported Locales** \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php\\n\\n   /**\\n     * Return an array of all supported Locales\\n     *\\n     * @return array\\n     */\\n     public function getSupportedLocales()\\n\\n    //Should be called like this:\\n    {{ LaravelLocalization::getSupportedLocales() }}\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nThis function will return all supported locales and their properties as an array.\n\n## **Get Supported Locales Keys** \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php\\n\\n/**\\n     * Returns supported languages language key\\n     *\\n     * @return array    keys of supported languages\\n     */\\n    public function getSupportedLanguagesKeys()\\n\\n    //Should be called like this:\\n    {{ LaravelLocalization::getSupportedLanguagesKeys() }}\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nThis function will return an array with all the keys for the supported locales.\n\n## **Set Locale** \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \" <?php\\n\\n\\t\\t/**\\n     * Set and return current locale\\n     *\\n     * @param  string $locale           Locale to set the App to (optional)\\n     *\\n     * @return string                   Returns locale (if route has any) or null (if route does not have a locale)\\n     */\\n    public function setLocale($locale = null)\\n\\n    //Should be called in a view like this:\\n    {{ LaravelLocalization::setLocale(optional string $locale) }}\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nThis function will change the application's current locale. If the locale is not passed, the locale will be determined via a cookie (if stored previously), the session (if stored previously), browser Accept-Language header or the default application locale (depending on your config file).\n\nThe function has to be called in the prefix of any route that should be translated (see Filters sections for further information).\n\n## **Get Current Locale** \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php\\n\\t\\t/**\\n     * Returns current language\\n     *\\n     * @return string current language\\n     */\\n    public function getCurrentLocale()\\n\\n    //Should be called in a view like this:\\n    {{ LaravelLocalization::getCurrentLocale() }}\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nThis function will return the key of the current locale.\n\n## **Get Current Locale Name** \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php\\n\\n\\t\\t/**\\n     * Returns current locale name\\n     *\\n     * @return string current locale name\\n     */\\n    public function getCurrentLocaleName()\\n\\n    //Should be called in a view like this:\\n    {{ LaravelLocalization::getCurrentLocaleName() }}\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nThis function will return current locale's name as string (English/Spanish/Arabic/ ..etc).\n\n## **Get Current Locale Direction** \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php\\n\\n/**\\n     * Returns current locale direction\\n     *\\n     * @return string current locale direction\\n     */\\n    public function getCurrentLocaleDirection()\\n\\n    //Should be called in a view like this:\\n    {{ LaravelLocalization::getCurrentLocaleDirection() }}\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nThis function will return current locale's direction as string (ltr/rtl).\n\n## **Get Current Locale Script** \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php \\n\\t\\t/**\\n     * Returns current locale script\\n     *\\n     * @return string current locale script\\n     */\\n    public function getCurrentLocaleScript()\\n\\n    //Should be called in a view like this:\\n    {{ LaravelLocalization::getCurrentLocaleScript() }}\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nThis function will return the ISO 15924 code for the current locale script as a string; \"Latn\", \"Cyrl\", \"Arab\", etc.\n\n## **Creating a language selector** \n\nIf you are supporting multiple locales in your project you will probably want to provide the users with a way to change language. Below is a simple example of blade template code you can use to create your own language selector.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<ul class=\\\"language_bar_chooser\\\">\\n    @foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)\\n        <li>\\n            <a rel=\\\"alternate\\\" hreflang=\\\"{{$localeCode}}\\\" href=\\\"{{LaravelLocalization::getLocalizedURL($localeCode) }}\\\">\\n                {{{ $properties['native'] }}}\\n            </a>\\n        </li>\\n    @endforeach\\n</ul>\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\n## **Translated Routes**\n\nYou can adapt your URLs depending on the language you want to show them. For example, http://url/en/about and http://url/es/acerca (acerca is about in spanish) or http://url/en/view/5 and http://url/es/ver/5 (view == ver in spanish) would be redirected to the same controller using the proper filter and setting up the translation files as follows:\n\nAs it is a middleware, first you have to register in on your **app/Http/Kernel.php** file like this:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"  <?php namespace App\\\\Http;\\n\\n    use Illuminate\\\\Foundation\\\\Http\\\\Kernel as HttpKernel;\\n\\n    class Kernel extends HttpKernel {\\n        /**\\n         * The application's route middleware.\\n         *\\n         * @var array\\n         */\\n        protected $routeMiddleware = [\\n            /**** OTHER MIDDLEWARE ****/\\n            'localize' => 'Mcamara\\\\LaravelLocalization\\\\Middleware\\\\LaravelLocalizationRoutes',\\n            // TRANSLATE ROUTES MIDDLEWARE\\n        ];\\n\\n    }\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php\\n\\n\\t// app/Http/routes.php\\n\\n    Route::group(\\n    [\\n        'prefix' => LaravelLocalization::setLocale(),\\n        'middleware' => [ 'localize' ] // Route translate middleware\\n    ],\\n    function()\\n    {\\n      /** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/\\n      Route::get('/', function()\\n      {\\n        // This routes is useless to translate\\n        return View::make('hello');\\n      });\\n\\n      Route::get(LaravelLocalization::transRoute('routes.about'),function(){\\n          return View::make('about');\\n      });\\n      Route::get(LaravelLocalization::transRoute('routes.view'),function($id){\\n          return View::make('view',['id'=>$id]);\\n      });\\n    });\\n\\n    /** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nIn the routes file you just have to add the ***LaravelLocalizationRoutes*** filter and the ***LaravelLocalization::transRoute*** function to every route you want to translate using the translation key.\n\nThen you have to create the translation files and add there every key you want to translate. I suggest to create a routes.php file inside your resources/lang/language_abbreviation folder. For the previous example, I have created two translations files, these two files would look like:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php\\n\\n\\t\\t// resources/lang/en/routes.php\\n    return [\\n      \\\"about\\\"       =>  \\\"about\\\",\\n      \\\"view\\\"        =>  \\\"view/{id}\\\", //we add a route parameter\\n      // other translated routes\\n    ];\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php\\n\\n\\t// resources/lang/es/routes.php\\n    return [\\n      \\\"about\\\"       =>  \\\"acerca\\\",\\n      \\\"view\\\"        =>  \\\"ver/{id}\\\", //we add a route parameter\\n      // other translated routes\\n    ];\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nOnce files are saved, you can access the following without any problem  \n\n  * http://url/en/about , \n  * http://url/es/acerca , \n  * http://url/en/view/5 \n  * http://url/es/ver/5 \n \nThe getLanguageBar function would work as desired and it will translate the routes to all translated languages (don't forget to add any new route to the translation file).\n\n##EVENTS\n\nYou can capture the URL parameters during translation if you wish to translate them too. To do so, just create an event listener for the ***routes.translation*** event like so\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php\\n\\nEvent::listen('routes.translation', function($locale, $attributes)\\n{\\n    // Do your magic\\n\\n    return $attributes;\\n});\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\nBe sure to pass the locale and the attributes as parameters to the closure. You may also use Event Subscribers, see: http://laravel.com/docs/events#event-subscribers\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"CONFIG\"\n}\n[/block]\n## **Config Files**\n\nIn order to edit the default configuration for this package you may edit ***config/tarns.php.*** Inside this file you will find all the fields that can be configured.","excerpt":"","slug":"trans","type":"basic","title":"Translator"}
. [block:api-header] { "type": "basic", "title": "USAGE" } [/block] Laravel Localization uses the URL given for the request. In order to achieve this purpose, a route group should be added into the ***routes.php*** file. It will filter all pages that must be localized. [block:code] { "codes": [ { "code": " // app/Http/routes.php\n\n Route::group(['prefix' => LaravelLocalization::setLocale()], function()\n {\n /** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/\n Route::get('/', function()\n {\n return View::make('hello');\n });\n\n Route::get('test',function(){\n return View::make('test');\n });\n });\n\n /** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/", "language": "php" } ] } [/block] Once this route group is added to the routes file, a user can access all locales added into ***supportedLocales*** ('en' and 'es' by default, look at the config section to change that option). For example, a user can now access two different locales, using the following addresses: [block:code] { "codes": [ { "code": " http://url-to-laravel/en\n http://url-to-laravel/es\n http://url-to-laravel", "language": "text" } ] } [/block] If the locale is not present in the url or it is not defined in ***supportedLocales***, the system will use the application default locale or the user's browser default locale (if defined in config file). Once the locale is defined, the locale variable will be stored in a session (if the middleware is enabled), so it is not necessary to write the /lang/ section in the url after defining it once, using the last known locale for the user. If the user accesses to a different locale this session value would be changed, translating any other page he visits with the last chosen locale. Template files and all locale files should follow the Lang class. [block:api-header] { "type": "basic", "title": "MIDDLEWARE" } [/block] Moreover, this package includes a middleware object to redirect all "non-localized" routes to the corresponding "localized". If a user navigates to http://url-to-laravel/test and the system has this middleware active and 'en' as the current locale for this user, it would redirect (301) him automatically to http://url-to-laravel/en/test. This is mainly used to avoid duplicate content and improve SEO performance. You have to register the middleware in the ***app/Http/Kernel.php*** file like this: [block:code] { "codes": [ { "code": " <?php namespace App\\Http;\n\n use Illuminate\\Foundation\\Http\\Kernel as HttpKernel;\n\n class Kernel extends HttpKernel {\n /**\n * The application's route middleware.\n *\n * @var array\n */\n protected $routeMiddleware = [\n /**** OTHER MIDDLEWARE ****/\n 'localize' => \\Mcamara\\LaravelLocalization\\Middleware\\LaravelLocalizationRoutes::class,\n 'localizationRedirect' => \\Mcamara\\LaravelLocalization\\Middleware\\LaravelLocalizationRedirectFilter::class,\n 'localeSessionRedirect' => \\Mcamara\\LaravelLocalization\\Middleware\\LocaleSessionRedirect::class\n // REDIRECTION MIDDLEWARE\n ];\n\n }", "language": "php" } ] } [/block] [block:code] { "codes": [ { "code": "<?php \n..\n// app/Http/routes.php\n\n Route::group(\n [\n 'prefix' => LaravelLocalization::setLocale(),\n 'middleware' => [ 'localeSessionRedirect', 'localizationRedirect' ]\n ],\n function()\n {\n /** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/\n Route::get('/', function()\n {\n return View::make('hello');\n });\n\n Route::get('test',function(){\n return View::make('test');\n });\n });\n\n /** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/", "language": "php" } ] } [/block] In order to activate it, you just have to attach this middleware to the routes you want to be accessible localized. If you want to hide the default locale but always show other locales in the url, switch the ***hideDefaultLocaleInURL*** config value to true. Once it's true, if the default locale is en (english) all URLs containing /en/ would be redirected to the same url without this fragment '/' but maintaining the locale as en (English). **IMPORTANT** - When ***hideDefaultLocaleInURL*** is set to true, the unlocalized root is treated as the applications default locale ***app.locale***. Because of this language negotiation using the Accept-Language header will NEVER occur when ***hideDefaultLocaleInURL*** is true. [block:api-header] { "type": "basic", "title": "HELPERS" } [/block] This package comes with some useful functions, like: ## **Get URL for an specific locale** [block:code] { "codes": [ { "code": " <?php\n\t\t \n\t\t /**\n * Returns an URL adapted to $locale\n *\n * @param string|boolean $locale Locale to adapt, false to remove locale\n * @param string|false $url URL to adapt in the current language. If not passed, the current url would be taken.\n * @param array $attributes Attributes to add to the route, if empty, the system would try to extract them from the url.\n *\n * @throws UnsupportedLocaleException\n *\n * @return string|false URL translated, False if url does not exist\n */\n public function getLocalizedURL($locale = null, $url = null, $attributes = array())\n\n //Should be called in a view like this:\n {{ LaravelLocalization::getLocalizedURL(optional string $locale, optional string $url, optional array $attributes) }}", "language": "php" } ] } [/block] It returns a URL localized to the desired locale. ## **Get Clean routes** [block:code] { "codes": [ { "code": "<?php\n\n\t /**\n * It returns an URL without locale (if it has it)\n * Convenience function wrapping getLocalizedURL(false)\n *\n * @param string|false $url URL to clean, if false, current url would be taken\n *\n * @return string URL with no locale in path\n */\n public function getNonLocalizedURL($url = null)\n\n //Should be called in a view like this:\n {{ LaravelLocalization::getNonLocalizedURL(optional string $url) }}", "language": "php" } ] } [/block] It returns a URL clean of any localization. ## **Get URL for an specific translation key** [block:code] { "codes": [ { "code": "<?php\n\n\t\t/**\n * Returns an URL adapted to the route name and the locale given\n *\n * @throws UnsupportedLocaleException\n *\n * @param string|boolean $locale Locale to adapt\n * @param string $transKeyName Translation key name of the url to adapt\n * @param array $attributes Attributes for the route (only needed if transKeyName needs them)\n *\n * @return string|false URL translated\n */\n public function getURLFromRouteNameTranslated($locale, $transKeyName, $attributes = array())\n\n //Should be called in a view like this:\n {{ LaravelLocalization::getURLFromRouteNameTranslated(string $locale, optional array $transKeyNames, optional array $attributes) }}", "language": "php" } ] } [/block] It returns a route, localized to the desired locale using the locale passed. If the translation key does not exist in the locale given, this function will return false. ## **Get Supported Locales** [block:code] { "codes": [ { "code": "<?php\n\n /**\n * Return an array of all supported Locales\n *\n * @return array\n */\n public function getSupportedLocales()\n\n //Should be called like this:\n {{ LaravelLocalization::getSupportedLocales() }}", "language": "php" } ] } [/block] This function will return all supported locales and their properties as an array. ## **Get Supported Locales Keys** [block:code] { "codes": [ { "code": "<?php\n\n/**\n * Returns supported languages language key\n *\n * @return array keys of supported languages\n */\n public function getSupportedLanguagesKeys()\n\n //Should be called like this:\n {{ LaravelLocalization::getSupportedLanguagesKeys() }}", "language": "php" } ] } [/block] This function will return an array with all the keys for the supported locales. ## **Set Locale** [block:code] { "codes": [ { "code": " <?php\n\n\t\t/**\n * Set and return current locale\n *\n * @param string $locale Locale to set the App to (optional)\n *\n * @return string Returns locale (if route has any) or null (if route does not have a locale)\n */\n public function setLocale($locale = null)\n\n //Should be called in a view like this:\n {{ LaravelLocalization::setLocale(optional string $locale) }}", "language": "php" } ] } [/block] This function will change the application's current locale. If the locale is not passed, the locale will be determined via a cookie (if stored previously), the session (if stored previously), browser Accept-Language header or the default application locale (depending on your config file). The function has to be called in the prefix of any route that should be translated (see Filters sections for further information). ## **Get Current Locale** [block:code] { "codes": [ { "code": "<?php\n\t\t/**\n * Returns current language\n *\n * @return string current language\n */\n public function getCurrentLocale()\n\n //Should be called in a view like this:\n {{ LaravelLocalization::getCurrentLocale() }}", "language": "php" } ] } [/block] This function will return the key of the current locale. ## **Get Current Locale Name** [block:code] { "codes": [ { "code": "<?php\n\n\t\t/**\n * Returns current locale name\n *\n * @return string current locale name\n */\n public function getCurrentLocaleName()\n\n //Should be called in a view like this:\n {{ LaravelLocalization::getCurrentLocaleName() }}", "language": "php" } ] } [/block] This function will return current locale's name as string (English/Spanish/Arabic/ ..etc). ## **Get Current Locale Direction** [block:code] { "codes": [ { "code": "<?php\n\n/**\n * Returns current locale direction\n *\n * @return string current locale direction\n */\n public function getCurrentLocaleDirection()\n\n //Should be called in a view like this:\n {{ LaravelLocalization::getCurrentLocaleDirection() }}", "language": "php" } ] } [/block] This function will return current locale's direction as string (ltr/rtl). ## **Get Current Locale Script** [block:code] { "codes": [ { "code": "<?php \n\t\t/**\n * Returns current locale script\n *\n * @return string current locale script\n */\n public function getCurrentLocaleScript()\n\n //Should be called in a view like this:\n {{ LaravelLocalization::getCurrentLocaleScript() }}", "language": "php" } ] } [/block] This function will return the ISO 15924 code for the current locale script as a string; "Latn", "Cyrl", "Arab", etc. ## **Creating a language selector** If you are supporting multiple locales in your project you will probably want to provide the users with a way to change language. Below is a simple example of blade template code you can use to create your own language selector. [block:code] { "codes": [ { "code": "<ul class=\"language_bar_chooser\">\n @foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)\n <li>\n <a rel=\"alternate\" hreflang=\"{{$localeCode}}\" href=\"{{LaravelLocalization::getLocalizedURL($localeCode) }}\">\n {{{ $properties['native'] }}}\n </a>\n </li>\n @endforeach\n</ul>", "language": "php" } ] } [/block] ## **Translated Routes** You can adapt your URLs depending on the language you want to show them. For example, http://url/en/about and http://url/es/acerca (acerca is about in spanish) or http://url/en/view/5 and http://url/es/ver/5 (view == ver in spanish) would be redirected to the same controller using the proper filter and setting up the translation files as follows: As it is a middleware, first you have to register in on your **app/Http/Kernel.php** file like this: [block:code] { "codes": [ { "code": " <?php namespace App\\Http;\n\n use Illuminate\\Foundation\\Http\\Kernel as HttpKernel;\n\n class Kernel extends HttpKernel {\n /**\n * The application's route middleware.\n *\n * @var array\n */\n protected $routeMiddleware = [\n /**** OTHER MIDDLEWARE ****/\n 'localize' => 'Mcamara\\LaravelLocalization\\Middleware\\LaravelLocalizationRoutes',\n // TRANSLATE ROUTES MIDDLEWARE\n ];\n\n }", "language": "php" } ] } [/block] [block:code] { "codes": [ { "code": "<?php\n\n\t// app/Http/routes.php\n\n Route::group(\n [\n 'prefix' => LaravelLocalization::setLocale(),\n 'middleware' => [ 'localize' ] // Route translate middleware\n ],\n function()\n {\n /** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/\n Route::get('/', function()\n {\n // This routes is useless to translate\n return View::make('hello');\n });\n\n Route::get(LaravelLocalization::transRoute('routes.about'),function(){\n return View::make('about');\n });\n Route::get(LaravelLocalization::transRoute('routes.view'),function($id){\n return View::make('view',['id'=>$id]);\n });\n });\n\n /** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/", "language": "php" } ] } [/block] In the routes file you just have to add the ***LaravelLocalizationRoutes*** filter and the ***LaravelLocalization::transRoute*** function to every route you want to translate using the translation key. Then you have to create the translation files and add there every key you want to translate. I suggest to create a routes.php file inside your resources/lang/language_abbreviation folder. For the previous example, I have created two translations files, these two files would look like: [block:code] { "codes": [ { "code": "<?php\n\n\t\t// resources/lang/en/routes.php\n return [\n \"about\" => \"about\",\n \"view\" => \"view/{id}\", //we add a route parameter\n // other translated routes\n ];", "language": "php" } ] } [/block] [block:code] { "codes": [ { "code": "<?php\n\n\t// resources/lang/es/routes.php\n return [\n \"about\" => \"acerca\",\n \"view\" => \"ver/{id}\", //we add a route parameter\n // other translated routes\n ];", "language": "php" } ] } [/block] Once files are saved, you can access the following without any problem * http://url/en/about , * http://url/es/acerca , * http://url/en/view/5 * http://url/es/ver/5 The getLanguageBar function would work as desired and it will translate the routes to all translated languages (don't forget to add any new route to the translation file). ##EVENTS You can capture the URL parameters during translation if you wish to translate them too. To do so, just create an event listener for the ***routes.translation*** event like so [block:code] { "codes": [ { "code": "<?php\n\nEvent::listen('routes.translation', function($locale, $attributes)\n{\n // Do your magic\n\n return $attributes;\n});", "language": "php" } ] } [/block] Be sure to pass the locale and the attributes as parameters to the closure. You may also use Event Subscribers, see: http://laravel.com/docs/events#event-subscribers [block:api-header] { "type": "basic", "title": "CONFIG" } [/block] ## **Config Files** In order to edit the default configuration for this package you may edit ***config/tarns.php.*** Inside this file you will find all the fields that can be configured.