Routes laravel translation - laravel

After much testing and searching, I can not find the solution.
My problem is that I have, for example the route '/services', '/servicios' in spanish.
If my website is in english, all texts are correctly shown in english, same in spanish. But the problem is with the text links, only appear in default locale.
In routes/web.php:
Route::get(trans('rutas.servicios'), 'ServiceController#index')->name('servicios')
File lang/es/rutas.php:
return [
'servicios' => '/servicios',
];
File lang/en/rutas.php:
return [
'servicios' => '/services',
];
and link html:
#lang('menus.servicios')
My goal is to use translated urls without using laravel prefix. That is to say:
https://www.myweb.com/services ~ english
https://www.myweb.com/servicios ~ spanish
share the same Route controller.
Any help? Lot of thanks for your time!
EDIT WITH SOLUTION:
I discovered that laravel performs route mapping before selecting the language. So what I did was to set the language before this, but the session and cookies variables load after this. But I finally discovered that the cached variables satisfied my needs.
At the top of function map() of RouteServiceProvider.php:
App::setLocale(Cache::get('locale'));
To store the selected locale:
Cache::put('locale', $locale, $minutes);

Related

Missing required parameter - routes with more than 2 parameters are not working with localization

I've been struggling lately with this problem and I really need some help.
So I implemented this tutorial: https://youtu.be/KqzGKg8IxE4 for adding localization to my project and it works well for routes that doesn't require another parameter besides the language. What I want to do is just keep the locale to the url as the first segment of the link, so it should follow this pattern:
example.com/en/shop
example.com/en/products/5/edit
but the routes with more parameters shouldn't be influenced by this prefix.
I have found more possible fixes for this, such as removing al the resource grouped routes and type them manually which would take forever, or override all the routes in order to use a parameter as a language switcher, for example 'example.com/shop?lang=en' and then implement an URL Generator macro, as answered in this question.
Also, I tried added an optional parameter in the language-switcher component, straight in my blade file like so
<language-switcher locale="{{ app()->getLocale() }}"
link-fr="{{ route(Route::currentRouteName(), ['locale' => 'fr', 'id' => '/{id?}']) }}"
link-en="{{ route(Route::currentRouteName(), ['locale' => 'en','id' => '/{id?}']) }}">
</language-switcher>
but what happens here is it just adds a random id for routes that do not have other parameter and only those which requires exactly 2 parameters work.
All these solutions are great BUT in my case none of them could be applied because as I said earlier, my requirement is to implement localization in such a way that the first segment of the link should be the language.
I feel there is an elegant way to solve this and I would appreciate any piece of advice since I no longer have any ideas on how this problem could be fixed.
Thank you !
You can get the current route parameters from the route object so something like:
<language-switcher locale="{{ app()->getLocale() }}"
link-fr="{{ route(Route::currentRouteName(), array_merge(request()->route()->parameters(), [ 'locale' => 'fr' ])) }}"
link-en="{{ route(Route::currentRouteName(), array_merge(request()->route()->parameters(), [ 'locale' => 'en' ])) }}">
</language-switcher>
Note this assumes that there's a matched route which is generally true but will not be true when displaying certain error pages like a 404 page when a route was not matched. So something to be mindful of

Consistency in Laravel localization

I have a laravel appication that I am building. I am building a multi language application which would have french and spanish and its url would be
www.example.com/fr/route/slug for french
www.example.com/es/route/slug for spanish
www.example.com/route/slug for english which is the main one
But I am very confused as to how I should go about maintaining the consistency from one url to another within the same language i.e. when I click on a link which is under french, what should be returned should still be french. e.g:
from
www.example.com/fr/route/slug1 to
www.example.com/fr/route/another_path to
www.example.com/fr/route/final_path which would be maintaing same language path
www.example.com/es/route/slug1 to
www.example.com/es/route/another_path to
www.example.com/es/route/final_path for spanish
www.example.com/route/slug1 to
www.example.com/route/another_path to
www.example.com/route/final_path for english
Also when I change from e.g. french to english the page must be consistent e.g.
www.example.com/fr/route/slug1 to
www.example.com/fr/route/another_path in french to english
www.example.com/route/another_path
What are the steps I should take? Any help would be appreciated. Thanks in advance.
To maintain this you can follow the below steps :
At change point of language at your website ( eg. Change language from dropdown ) , store selected value in session and then your page should be reload
Then you have to create one middelware to manage the localization.
You just have to simply write few line of code in handle method of the Middleware.
$lang = Session::get("language");
App::setLocale($lang);
Thats it, this will manage your consistency.
You should add this group for all your route
Route::group(['middlewareGroups' => 'web', 'prefix' => '{local}'], function () {
and then make middleware where you catch the local and then :
public function handle($request, Closure $next)
{
App::setLocale($locale);
}
And apply it by adding it in your $middleware array located in the Http/kernel.php file

Laravel 4 multilanguage routing

I'm trying to implement a multilanguage routing.
The problem I'm facing lies in pointing out a route translated to more than one language, to a controller of its own. Let me give a simple example:
Let's say I have a simple route as follows
Route::get('/contacts', 'PageController#contacts');
And I want the same controller to be used for another route, but this time translated in another language, german for example.
Route::get('/kontakte', 'PageController#contacts');
For a simple webiste, with no more than 5-6 pages, writing down the routes for all languages would not be such a pain, but for more complex website, with huge amount of pages and having more than 2 available languages, a solution like this would be ugly.
I found an older topic here, where the author suggested loading a route.php file depending on the currently selected language. But still, this would require more than one file to be edited for further need.
A point of suggestion or currently working solution would be really appreciated.Thanks for your help.
Just some quick thoughts:
A solution can be to do grouping routes with a prefix like '/en/' and '/de/'.
So you will have /en/contact and /de/contact.
docs for this: http://laravel.com/docs/routing#route-prefixing
This way you can just create a loop through your available languages, and register the route.
The con here that you can't have a /de/kontake or /kontakte url, because there is 1 loop with routes, and they probably will be in English.
<?php
$languages = array('en', 'de');
foreach($langauges as $language)
{
Route::group(array('prefix' => $language), function()
{
Route::get('/', 'HomeController#index');
Route::get('contact', 'HomeController#contact');
});
}
A second solution will be to store all your routes in a database (or just an array to test it in the beginning)
You will need some Page and PageLocal models for it.
Page: id, name, controller
example: 1, contact, PageController#contact
PageLocal: id, page_id, language, slug
example: 1, 1, en, contact
example: 1, 1, de, kontakte
Loop through all Pages, lazy load the PageLocal with it, and register the routes.
You can throw out the language column if you like, but lookout for duplicate slugs. Thats why a language prefix is a good idea. (And perhaps it will help with some SEO...)
<?php
$Pages::with('Locals')->all();
foreach($Pages as $Page)
{
foreach($Page->Locals as $PageLocal)
{
Route::get($PageLocal->language.'/'.$PageLocal->slug, $Page->controller);
}
}
And after that you still have to think about url's without a language prefix, get and post routes, etc, etc, but this will get something started.

Different URL keys for different language CMS pages

I'm currently setting up a Magento shop that will support a few different languages.
One issue that I ran into is that I can't find out how to link two CMS pages together, so that when a user switches their language, they are automatically forwarded to the current CMS page but in their preferred language. One option would be to use the same URL key for both pages, but that wouldn't be very user friendly as some users would then see URL keys not in their native language.
Let me give you an example:
I have an "About us" page. In the English version of the store, the URL of that page is /about-us. Now a German user lands on that page and switches his language. But because the German equivalent to "About us" is "Über uns", the German version of that page is at /ueber-uns, so the user would be presented a 404 page because no German version of /about-us exists.
Does anybody know how to solve this issue?
Update: Did some more research and found nothing. I can't believe I am the only one with this problem? The go-to solution, using the same URL key for all languages, seems very ugly and not very user friendly!
So, the only solution that I found was to manually create a redirect for each page in the Magento Rewrite Rules. Do do that, go to Catalog -> URL Rewrite Management and add each page in the following format:
So if a user is using the Francais store view and requests /url-in-english, the redirect will kick in and redirect the user to /url-in-french.
This is of course not an ideal solution, it would be preferred if two pages could be "linked" directly, but I suppose I will have to use this for the moment. If anybody comes up with a better solution feel free to add yours!
I have seen this bug in Magento CE 1.8.0.0. The problem here was a wrong assignment in \app\code\core\Mage\Core\Model\Url\Rewrite\Request.php.
To solve this problem it is sufficient to change the assignment of $fromStore in the protected function _rewriteDb() within the Mage_Core_Model_Url_Rewrite_Request class from
$fromStore = $this->_request->getQuery('___from_store');
to
$fromStore = Mage::getModel('core/store')->load($this->_request->getQuery('___from_store'), 'code')->getId();
with the result that we can access the $stores array with the right key (with the store id instead of the store code). With this the if statement
if (!empty($stores[$fromStore])) {
works in the right way.
As a reminder: Do not modify core files. Just copy \app\code\core\Mage\Core\Model\Url\Rewrite\Request.php to \app\code\local\Mage\Core\Model\Url\Rewrite\Request.php before any change.
You will find this answer in German here: Rewrite von Seiten in verschiedenen Sprachen und verschiedenen URL Keys in Magento
Above solution works but takes a while. We just did the following to rewrite the language changer url when on a cms page to go to the base url:
Add the following code to app/design/frontend/default/template_name/template/page/switch/languages.html after the part where the $url variable is filled (on our it was like
$url = /*explode( '?',*/$_lang->getCurrentUrl()/*);*/;
so we added the following:
if(($this->getRequest()->getModuleName() == 'cms') && strpos($url,'.com/')){$url = strstr($url, '.com/', true) . '.com/';}
elseif(($this->getRequest()->getModuleName() == 'cms') && strpos($url,'.de/')){$url = strstr($url, '.de/', true) . '.de/';}
elseif(($this->getRequest()->getModuleName() == 'cms') && strpos($url,'.nl/')){$url = strstr($url, '.nl/', true) . '.nl/';}
What I did here is check if on a cms page and check if the url contains either .com/ ; .de/ or .nl and strip the part before then add the domain extension back.
in our example: http://www.mega-watch.com/about-us?blabla will become http://www.mega-watch.com/
Hope this helps someone out..

SEO-friendly URLs in CodeIgniter without the use of slugs?

Is there a way (via routing) in CodeIgniter to change:
example.com/category/4 to example.com/category/foo-bar
where Foo Bar is the name of category 4 in the database?
Access from the SEO-friendly URL should be allowed, but access via the integer should cause a 404 error.
This should also work dynamically, where any integer is automatically converted to a URL-safe version of its corresponding category name.
I've seen a few solutions that use 'slugs'... is there a decent alternative?
Thanks.
I've only been working with CodeIgniter for the past couple of months in my spare time, so I'm still learning, but I'll take a shot at this (be gentle):
There is a url_title() function in the URL Helper (which will need loaded, of course) that will change Foo Bar to foo-bar.
$name = 'Foo Bar';
$seo_name = url_title($name, TRUE);
// Produces: foo-bar
http://codeigniter.com/user_guide/helpers/url_helper.html
The URL helper strips illegal characters and throws in the hyphens by default (underscores, by parameter) and the TRUE parameter will lowercase everything.
To solve your problem, I suppose you could either do a foreach statement in your routes.php file or pass the url_title() value to the URL, rather than the ID, and modify your code to match the url_title() value with its category name in the DB.
Afaik the link between 4 and "foo-bar" has to be stored in the DB, so you'll have to run some queries. This is usually not done via routing in CI. Also routing just points a URL to a controller and function and has little to do with url rewriting.
Why don't you want to use slugs?
You could try storing the search engine friendly route in the database using this method or this one.
I wouldn't recommend throwing a 404. Use the canonical link tag in the instead if your worried about Google indexing both http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html.
But if you really want to I guess you could write a function that is called during the pre_controller hook http://codeigniter.com/user_guide/general/hooks.html that checks to see if the URL has an integer as the second segment then call the show_404() method. Perhaps a better solution when writing this function would be to redirect to the SEO friendly version.
Is there a way (via routing) in CodeIgniter to change:
example.com/category/4 to example.com/category/foo-bar
where Foo Bar is the name of category 4 in the database?
Yes.
Using CI 3,
http://www.codeigniter.com/user_guide/general/routing.html
Use Callbacks, PHP >= 5.3
$route['products/([a-zA-Z]+)/edit/(\d+)'] = function ($product_type, $id)
{
return 'catalog/product_edit/' . strtolower($product_type) . '/' . $id;
};
You can route to call a function to extract the name of the category.
Hope I answered your question and can help more people to like codeigniter as I believe it's speedy and light.
Slugs usage is important to make web application more secure which i think is important.
A better recommendation will be to use route to give you a better solution.
$route['(:any)/method/(:num)'] = 'Class/method';
or
$route['(:any)/method/(:num)'] = 'Class/method/$1';
$route['(:any)/gallery/(:num)'] = 'Class/gallery/$1';
base_url()/business-services/gallery/6
base_url()/travel/gallery/12
how to modify routes in codeigniter
Have fun :)

Resources