codezero-be / laravel-localized-routes Goto Github PK
View Code? Open in Web Editor NEW⭐️ A convenient way to set up and use localized routes in a Laravel app.
License: MIT License
⭐️ A convenient way to set up and use localized routes in a Laravel app.
License: MIT License
Hi!
When I try to redirect to a localized route with the Route::localizedUrl method, if the URL has a final slash it will redirect to the same URL, but with the public/ prefix.
For example, Route::localizedUrl("products") will redirect to "it/products" but Route::localizedUrl("products/") will redirect to "public/it/products".
I have the last version of the package.
Any idea?
Thanks!
Mauro
Hello,
Thank you for this awesome package, but I met an issue : I can't make it work with localizer.
I have enabled the config boolean, I've also added the localizer middleware in addition to the LocalizedRoute one, but it did not work : I can't get my locale detection working.
I use the locale switcher extension in order to make my website work with en, fr and de.
Even if german is detected, it's always overwritten with the default locale. I dug deeper in the localizer package and output logs (in order to avoid breaking session and cookies storage methods) from stores:
[2021-04-26 13:57:45] local.DEBUG: should CodeZero\Localizer\Stores\SessionStore::store de from CodeZero\Localizer\Stores\SessionStore
[2021-04-26 13:57:45] local.DEBUG: should CodeZero\Localizer\Stores\CookieStore::store de from CodeZero\Localizer\Stores\CookieStore
[2021-04-26 13:57:45] local.DEBUG: should store de from CodeZero\Localizer\Stores\AppStore::store
[2021-04-26 13:57:45] local.DEBUG: should CodeZero\Localizer\Stores\SessionStore::store en from CodeZero\Localizer\Stores\SessionStore
[2021-04-26 13:57:45] local.DEBUG: should CodeZero\Localizer\Stores\CookieStore::store en from CodeZero\Localizer\Stores\CookieStore
[2021-04-26 13:57:45] local.DEBUG: should store en from CodeZero\Localizer\Stores\AppStore::store
[2021-04-26 13:57:46] local.DEBUG: from route/web.php: App::getLocale -> en
What did I miss ?
Hi @ivanvermeyen ✋
I just switched my base app on L7 and I am currently switching to the new route model key binding (page/{page:slug}
).
I am wondering if there would be a way to avoid to override the Model route key in the getRouteKey()
method as it was required before. Indeed, I would like to get my pages from the slugs in the front and from the ids in the backoffice.
But currently, the Route::localizedUrl($localeKey)
seems not be aware of this new system of binding and renders the localized URL with the route key defined in the getRouteKey()
method without taking care of an eventual declared field (could be the field when declared and the result of this method when nothing is declare).
I don't if I am very clear, everything become such complex when we speak about routes 😄
I wanted to use localization slugs, and i have this controller action at the moment to change the locale.
public function setLocale($locale){
session()->put('locale', $locale);
App::setLocale($locale);
if (Auth::check()) {
$user = Auth::user();
$user->update(['language' => $locale]);
}
return redirect()->back();
}
If i call this method while i'm on example.com i will still get redirected to example.com instead of example.com/locale.
When I click on the next link, everything seems to work fine and adds the slug to the url as expected.
Is there a way to use the redirect->back() and also add the right slug to the url?
I am setting up this package for an existing website and I'm running into issues getting the redirects working (e.g. /about
to /en/about
)
I've added the following to the bottom of my routes/web.php
file as instructed:
Route::fallback(\CodeZero\LocalizedRoutes\Controller\FallbackController::class)
->middleware(\CodeZero\LocalizedRoutes\Middleware\SetLocale::class);
The problem, however, is that doing this causes Laravel to throw an error, "Invalid Route Action". It shows the error page when you visit either /about
or /en/about
, and even when you run php artisan route:clear
.
I'm currently on Laravel 8, running PHP 7.4.
Hi, Im have problem with:
Hey guys,
Apologies for this, but after a few hours I can't manage to route bind models that use this package translatable trait.
My goal here is to make the urls dynamic such as:
/en/article/slug-in-english
/pt/artigo/slug-in-portuguese
Using this package alongside => https://github.com/Astrotomic/laravel-translatable
In routes.php I have used:
Route::get(Lang::uri('article').'/{article:slug}', 'ArticleController@show')->name('article.show');
Then, in my language switcher dropdown:
\Route::localizedUrl($lang)
The problem so far, is that the dropdown only displays the slugs in english. It changes the 2 char locale ("en" => "pt") but not the slug itself.
Article Model:
<?php
/*
* Copyright (c) 2021 Ceuton.
*/
namespace App\Models;
use App\Http\Controllers\Controller;
use Astrotomic\Translatable\Contracts\Translatable as TranslatableContract;
use Astrotomic\Translatable\Translatable;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Str;
use Throwable;
class Article extends Model implements TranslatableContract
{
use Translatable;
const STATUS_UNPUBLISHED = 0;
const STATUS_PUBLISHED = 1;
const STATUS_DRAFT = 2;
const STATUS_SCHEDULED = 3;
protected $fillable = [
'featured_img',
'scheduled_at',
'status',
'created_at',
'updated_at'
];
public array $translatedAttributes = [
'slug',
'title',
'body'
];
public function categories(): BelongsToMany
{
return $this->belongsToMany(Category::class);
}
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class);
}
public function keywords(): BelongsToMany
{
return $this->belongsToMany(Keyword::class);
}
public function medias(): MorphToMany
{
return $this->morphToMany(Media::class, 'mediable');
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
public function getRouteKeyName(): string
{
return 'slug';
}
public function getRouteKey($locale = null)
{
try {
$slugs = [];
foreach (config('constants.locales') as $key => $name)
if($this->hasTranslation($key))
$slugs[$key] = $this->translate($key)->slug;
if($locale)
return $slugs[$locale];
return $slugs[app()->getLocale()];
} catch (Throwable $exception) {
return $this->slug;
}
}
public function getRoute(): string
{
try {
return route('article.show', [$this->getRouteKey()], true, app()->getLocale());
} catch (Throwable $exception) {
return "#";
}
}
public function getTitle($size = null, $locale = null)
{
try {
if(!$locale)
$locale = app()->getLocale();
if ($size)
return Str::limit($this->{'title:' . $locale}, $size);
return $this->{'title:' . $locale};
} catch (Throwable $exception) {
return "---";
}
}
public function getExcerpt($size = null): string
{
try {
if ($size)
return Str::limit(strip_tags($this->{'body:' . app()->getLocale()}), $size);
return strip_tags($this->{'body:' . app()->getLocale()});
} catch (Throwable $exception) {
return "---";
}
}
public function getBody($size = null): string
{
try {
if ($size)
return Str::limit($this->{'body:' . app()->getLocale()}, $size);
return $this->{'body:' . app()->getLocale()};
} catch (Throwable $exception) {
return "---";
}
}
public function getAdvertisedBody(): string
{
try {
return (new Controller())->injectAdv($this->getBody());
} catch (Throwable $exception) {
return "---";
}
}
public function getFeaturedImg(): string
{
try {
return asset_cdn('storage/uploads/' . $this->medias()->firstOrFail()->name);
} catch (Throwable $exception) {
return asset_cdn('assets/img/featured.jpg');
}
}
public function getFeaturedImgCredits()
{
try {
return $this->medias()->firstOrFail()->credits;
} catch (Throwable $exception) {
return null;
}
}
public function getMainCategory($attribute = "slug")
{
try {
return $this->categories()->firstOrFail()->$attribute;
} catch (Throwable $exception) {
return "other";
}
}
public function getKeywords()
{
try {
$keywords = collect([]);
$keywords->merge($this->categories()->pluck('name'));
$keywords->merge($this->tags()->pluck('name'));
return $keywords->toArray();
} catch (Throwable $exception) {
return collect([]);
}
}
public function getStatusElements()
{
switch ($this->status) {
case Article::STATUS_UNPUBLISHED:
return '<span class="badge badge-danger">Lixo</span>';
case Article::STATUS_PUBLISHED:
return '<span class="badge badge-success">Publicado</span>';
case Article::STATUS_SCHEDULED:
return '<span class="badge badge-primary">Agendado</span>';
case Article::STATUS_DRAFT:
return '<span class="badge badge-warning">Rascunho</span>';
}
}
public function resolveRouteBinding($value, $field = null)
{
return $this->translations()->where($field ?? $this->getRouteKeyName().'->'.app()->getLocale(), $value)->firstOrFail();
}
}
ArticleTranslation:
<?php
/*
* Copyright (c) 2021 Ceuton.
*/
namespace App\Models;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ArticleTranslation extends Model
{
use Sluggable;
public $timestamps = false;
protected $fillable = [
'locale',
'slug',
'title',
'body',
];
public function article(): BelongsTo
{
return $this->belongsTo(Article::class, 'article_id', 'id');
}
public function sluggable(): array
{
return [
'slug' => [
'source' => 'title'
]
];
}
}
Hello :)
I believe I've found a limitation on this package or I'm just doing something wrong.
My use case kinda simple, in a route with two diferent model bindings where the model implements the ProvidesRouteParameters
when using Route::localizedUrl()
the package just assumes the first binding and throws an error saying the 2nd parameter is missing.
For example:
$router->localized(function ($router) {
$router->get('/{foo}/{bar}', function(ModelFoo $foo, ModelBar $bar) {})
});
Models examples:
class ModelFoo extends Model implements ProvidesRouteParameters
{
public function getRouteKeyName()
{
return 'slug';
}
public function getRouteParameters($locale = null)
{
return [$this->slug[$locale];
}
}
class ModelBar extends Model implements ProvidesRouteParameters
{
public function getRouteKeyName()
{
return 'slug';
}
public function getRouteParameters($locale = null)
{
return [$this->slug[$locale];
}
}
The error is something like this:
Missing required parameter for [Route: en.route.name [URI: /{foo}/{bar}] [Missing parameter: bar].
Is it ok for you if I open a PR to attempt to solve this?
Thank you.
Hello!
I have added the following languages: 'supported-locales' => ['en', 'uk'], 'redirect_to_localized_urls' => true, 'use_localizer' => true,
.
How can I redirect from index to site.com/uk/
OR site.com/en/
?
<?php
use Illuminate\Support\Facades\Route;
Route::fallback(\CodeZero\LocalizedRoutes\Controller\FallbackController::class)
->middleware(\CodeZero\LocalizedRoutes\Middleware\SetLocale::class);
Route::localized(function () {
Route::get('/', function () {
return view('welcome');
});
});
And is it possible to make an automatic redirect with HTTP_ACCEPT_LANGUAGE header preemption?
First of all, thanks for this beautiful package, Ivan. It requires some configuration, but the helpers feel very intuitive; almost like they should be native.
I'm running into something unexpected, however. Please consider the following setup:
// config/localized-routes.php
return [
'supported-locales' => ['en', 'nl'],
'omit_url_prefix_for_locale' => null,
'redirect_to_localized_urls' => true,
'redirect_status_code' => 301,
'404_view' => 'errors.404',
'use_locale_middleware' => true,
'use_localizer' => false,
];
// routes.web.php
Route::localized(function () {
Route::get('/', function () {
return view('welcome');
});
});
Route::fallback(\CodeZero\LocalizedRoutes\Controller\FallbackController::class)
->middleware(\CodeZero\LocalizedRoutes\Middleware\SetLocale::class);
Whenever I visit /
I get redirected to /nl
. This in itself is surprising given that use_localizer
is set to false
and the configured default app locale is en
. What's stranger still is that whenever I request /en
(which I believe should set and persist the en
locale), and subsequently request /
, it does not redirect me to /en
but to /nl
again. (The same happens when use_localizer
is enabled.)
In other words, the locale (app, cookie, and session) does not seem to get updated by visiting a slugged URL. Perhaps, I'm missing something, but I feel I've RTFM'ed a few times now 😅
I have a requirement to include the locale AND the country in the URL like this:
/ch-fr/entreprises
/de-en/companies
/at-de/unternehmen
I am also going to have multiple countries with the same locale:
/ch-de/unternehmen
/de-de/unternehmen
/at-de/unternehmen
This basically works by setting the supported-locales
config value to something like this:
'supported-locales' => [
'ch-de', 'ch-fr', 'ch-it', 'ch-en',
'de-de', 'de-en',
'at-de', 'at-de',
],
However, I think this has some disadvantages, for example, now I have to have 3 versions for German in the lang
directory and keep them in sync: ch-de
, de-de
and at-de
. Having only one de
directory no longer works. Other third party packages like spatie/laravel-translatable do not work well with this approach.
In order to avoid duplication, I would have proposed a syntax like this:
'supported-locales' => [
'de' => [
'ch-de',
'de-de',
'at-de',
],
'en' => [
'ch-en',
'de-en',
'at-en',
],
'fr' => [
'ch-fr',
],
],
But I guess this would break the domains/subdomains feature. So I'm wondering what's the best approach to deal with this?
Any suggestions are highly appreciated!
Hi,
I'm trying to access other locales for exemple localhost.com/fr
but it always returning page route
i want to have this :
localhost.com/{slug}
localhost.com/fr/{slug}
localhost.com/pt/{slug}
my config :
// localized-routes.php
return [
'supported-locales' => ['en', 'fr', 'pt'],
'omit_url_prefix_for_locale' => 'en',
'use_locale_middleware' => true,
'use_localizer' => false,
];
// web.php
Route::localized(function () {
Route::get('/', 'Root\IndexController@index')->name('index');
Route::get('/{slug}', function ($slug) {
return Page::where('slug', $slug)->first();
})->name('page');
});
Thanks for your work
It seems to be a common practice to redirect any unregistered URL that does not have a supported locale to its localized version:
Accessing /dashboard
would redirect to /en/dashboard
if en
is the detected locale. If /en/dashboard
is a registered route, it would just show that page.
Accessing /non/existing/route
would redirect to /en/non/existing/route
if en
is the detected locale, which would then show a 404 page in the appropriate language.
Accessing /nl/non/existing/route
would show the 404 page in Dutch, if nl
is a supported locale.
I will need to research how to implement this with and/or without using fallback routes.
The function doesn't work as per the documentation, the problem is that it doesn't return the url with the passed locale but always takes the one currently in session/cookie, using tinker instead the url is returned without the locale passed as argument.
$url = route('about', [], true, 'locale');
Laravel Framework 8.76.2
Hi, first of all thank you for making this, it's a nice little time saver for i18n apps and websites.
There's one small issue when using this in Laravel 6. Routes with model bindings (when using slugs instead of IDs) don't work out of the box.
For example let's say your default locale is set to "en" and you have this route:
Route::get(Lang::uri('articles/{article}'), 'ArticlesController@show')
Now this is what happens:
en/articles/en-slug
- works
de/artikel/de-slug
- doesn't work
de/artikel/en-slug
- works
This happens because \Illuminate\Routing\Middleware\SubstituteBindings::class middleware is executed before your middleware that sets the locale.
In order to make it work properly you have to add \CodeZero\LocalizedRoutes\Middleware\LocalizedRouteLocaleHandler::class
to $middlewarePriority
array inside Http/Kernel.php
and place it before \Illuminate\Routing\Middleware\SubstituteBindings::class
protected $middlewarePriority = [
...
\CodeZero\LocalizedRoutes\Middleware\LocalizedRouteLocaleHandler::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
...
];
Hope this helps someone :)
Thanks for this awesome package! 👍
I'm trying to figure this out for a long time...
I have 2 locales, ['en', 'he']
.
I set omit_url_prefix_for_locale
to 'en'
, so the en
locale is unprefixed.
But now whenever someone visits the default url, the locale is changed back to the default locale.
Is it possible to redirect to the previously chosen url (using the cookie/session/browser)?
In other words, if I switch to he
, then a day later visit the default url, I should be redirected to the he
locale.
Great package! :)
When I define my routes explicitly like this...
Route::get(Lang::uri('companies'), [CompanyController::class, 'index'])->name('companies.index');
Route::get(Lang::uri('companies/create'), [CompanyController::class, 'create'])->name('companies.create');
Route::get(Lang::uri('companies/{company}'), [CompanyController::class, 'show'])->name('companies.show');
Route::get(Lang::uri('companies/{company}/edit'), [CompanyController::class, 'edit'])->name('companies.edit');
Route::post(Lang::uri('companies'), [CompanyController::class, 'store'])->name('companies.store');
Route::put(Lang::uri('companies/{company}/'), [CompanyController::class, 'update'])->name('companies.update');
Route::delete(Lang::uri('companies/{company}/'), [CompanyController::class, 'destroy'])->name('companies.destroy');
... everything works as expected:
GET|HEAD de/unternehmen ............................ de.companies.index › CompanyController@index
POST de/unternehmen ............................ de.companies.store › CompanyController@store
GET|HEAD de/unternehmen/hinzufügen ................. de.companies.create › CompanyController@create
GET|HEAD de/unternehmen/{company} .................. de.companies.show › CompanyController@show
PUT de/unternehmen/{company} .................. de.companies.update › CompanyController@update
DELETE de/unternehmen/{company} .................. de.companies.destroy › CompanyController@destroy
GET|HEAD de/unternehmen/{company}/bearbeiten ....... de.companies.edit › CompanyController@edit
But when I use the shorthand...
Route::resource('companies', CompanyController::class)
... the routes are not translated correctly:
GET|HEAD de/companies .............................. de.companies.index › CompanyController@index
POST de/companies .............................. de.companies.store › CompanyController@store
GET|HEAD de/companies/create ....................... de.companies.create › CompanyController@create
GET|HEAD de/companies/{company} .................... de.companies.show › CompanyController@show
PUT|PATCH de/companies/{company} .................... de.companies.update › CompanyController@update
DELETE de/companies/{company} .................... de.companies.destroy › CompanyController@destroy
GET|HEAD de/companies/{company}/edit ............... de.companies.edit › CompanyController@edit
And this is what my /lang/de/routes.php looks like:
return [
'companies' => 'unternehmen',
'create' => 'hinzufügen',
'edit' => 'bearbeiten',
];
What am I doing wrong? Is it even possible to use Route::resource()
with this package?
Hello !
Is it possible to generate routes correctly with Inertia using your package ?
With Inertia, the Ziggy library is used. After debugging, my route list contains for example:
And calling route('dashboard') function in inertia does not work.
Hello,
Firstly, thanks for this awesome package.
It's working fine amazing, but I need to override the route helper function.
I see you have added "if( !function_exists ('route'))" to your helper, however, If i declare the same route function in my own laravel application, it gives an error saying its already declared in this package.
So, question is, how can I override this?
https://github.com/codezero-be/laravel-localized-routes/blob/master/src/helpers.php
It would be convenient to have a short Route::isFallback()
method, for example when generating a locale switcher like this:
@foreach(config('localized-routes.supported-locales') as $locale)
@if ((Route::isLocalized() || Route::isFallback()) && ! App::isLocale($locale))
<a href="{{ Route::localizedUrl($locale) }}">{{ strtoupper($locale) }}</a>
@endif
@endforeach
Right now, Laravel doesn't have this method, so I added a macro to the boot()
method of the RouteServiceProvider
of my project:
Route::macro('isFallback', function () {
return Route::current() && Route::current()->isFallback;
});
I'm not sure if this is something I should add to this package or not, just for convenience...
For now, I'm just leaving it here for reference.
Enable the combined use of localized domains and slugs.
Fictional use case:
Locale | URL | Description |
---|---|---|
en |
https://example.be/en |
English |
nl |
https://example.be/nl |
Dutch |
nl_BE |
https://example.be/nl |
Belgium, Dutch |
fr_BE |
https://example.be/fr |
Belgium, French |
nl_NL |
https://example.nl/ |
Netherlands, Dutch (no slug) |
fr_FR |
https://example.fr/ |
France, French (no slug) |
Possible configuration (related to suggested configuration in #20):
'supported-locales' => ['en', 'nl', 'nl_BE', 'fr_BE', 'nl_NL', 'fr_FR'],
'domains' => [
'en' => 'example.be',
'nl' => 'example.be',
'nl_BE' => 'example.be',
'fr_BE' => 'example.be',
'nl_NL' => 'example.nl',
'fr_FR' => 'example.fr',
],
'slugs' => [
'en' => 'en',
'nl' => 'nl',
'nl_BE' => 'nl',
'fr_BE' => 'fr',
'nl_NL' => null, // no slug
'fr_FR' => null, // no slug
],
This is just a first idea of how this might look. Will need to work out if any misconfigurations can happen (we need to be able to detect the locale based on the URL) and how to handle that.
Hi there !
First, thanks for the good work, this package is quite pleasant to use.
I managed to build a language selector which allows to navigate between language and take care of translated and static URL : I can, for example, switch from /about
to /a-propos
.
But I wonder how you would build a language selector which take care about the translated dynamic content.
For example, if I take your example Post
class with translated slugs and a route declared like this posts/{slug}
, how would you manage to switch with a language selector from /posts/dynamic-en-slug
to /posts/slug-fr-dynamique
, from a post detail page, by clicking on the FR
language flag (which the role is to send toward the exact same page translated in the targeted language)?
I imagine you already achieved this kind of things ?
Thanks by advance !
When adding the SetLocale
middleware that comes with this package, it makes sense that the detection "just works".
Right now there is some basic detection logic in this package in case the use_localizer
setting is disabled. Additionally, if you want to change the underlying detection configuration, you need to publish the config file of the localizer
package.
Therefor, it might be more developer friendly to just merge the localizer
package with this one.
Hi, thanks for your library first of all!
I'm having a problem using Route::localizedUrl
, in particular, some routes are defined in this way:
Route::get('/form-and-function', 'Webkul\Shop\Http\Controllers\FrontendController@formAndFunction')->defaults('_config', [
'view' => 'shop::layouts.pages.form-and-function'
])->name('shop.frontend.pages.form_and_function');
so calling localizedUrl
will return:
https://example.com/it/form-and-function?_config%5Bview%5D=shop%3A%3Alayouts.pages.form-and-function
is there any way to remove all the parameters from the url and keep only https://example.com/it/form-and-function
Thanks
Hello,
I'm looking for a way to set the "supported-locales" configuration from db data. I can't find a way to do this properly.
Any ideas ?
I've made a dropdown to switch the language but it didn't work "on the fly", only after clicking the link twice the page loaded with the selected language. I was able to do it by replacing the SetLocale middleware and adding to the handle function:
App::setLocale($locale);
Carbon::setLocale($locale);
Date::setLocale($locale);
I don't know if anyone had the same problem but here's the solution I've found.
Thanks, and great package by the way!
Hi & merci voor de package :)
Are you willing to accept a PR that manually registers the package's dependencies in its service provider rather than relying on autodiscovery?
We have intentionally disabled autodiscovery in a monolith we're currently working on that serves multiple apps. But since the package does not manually register its own dependencies, we have to register 3 or 4 (not sure) service providers in each app to make the package work, which is quite cumbersome.
This should not break anything, just a convenience thing for the 1% that does not use autodiscovery 😄. The framework also skips registrations when a provider has already been registered.
Hello, Ive problems using livewire. All works fine, but when I type the input, data refresh and dissapear data from views/livewire/filtro.
When I click on url, data comes well.
Ive to refresh url to view data.
Ive tried displya blade without Front Controller, clear cache, clear routes
Http/Livewire/Filtro
`use Livewire\WithPagination;
class Filtro extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
protected $queryString = ['marca'];
public $marca;
public function render()
{
return view('livewire.filtro', [
'productos' => Producto::where('deleted',0)
->where('marca', 'like', '%'.$this->marca.'%' )->paginate(20)
]);
}
}`
routes/web
`<?php
use Illuminate\Support\Facades\Route;
/* |
---|
Web Routes |
-------------------------------------------------------------------------- |
*/
// Localized
Route::localized(function () {
Route::get('/anuncios', function () {
return view('front.anuncios');
});
Route::get('/', function () {
return view('front.index');
});
Route::get('/index', [App\Http\Controllers\FrontController::class, 'index'])->name('front.index');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::fallback(\CodeZero\LocalizedRoutes\Controller\FallbackController::class)
->middleware(\CodeZero\LocalizedRoutes\Middleware\SetLocale::class);`
views/livewire/filtro
`
<div class="listing__text__top">
<div class="listing__text__top__left">
<h5>Todoterrenos</h5>
<span>{{ $productos->count() }} Resultados</span>
<input type="text" class="form-control" placeholder="Search" wire:model.debounce.1000ms="marca" />
<div wire:loading>
Processing ...
</div>
<div wire:offline>
You are now offline.
</div>
<div class="listing__text__top__right">Ordenar <i class="fa fa-sort-amount-asc"></i></div>
</div>
@if($producto->garantizado === 'Si')
<div class="listing__item__text__info__right pr-3">Garantizado</div>
@endif
<div class="">
<a href="{{ route('front.detalle', $producto->titulo_slug) }}"><img src="{{ asset('img/productos/'.$producto->imagen_1)}}" height="150" alt="..." class="rounded float-left pr-2"></a>
</div>
<div class="listing__item__text">
<div class="listing__item__text__inside ">
<h5><a href="{{ route('front.detalle', $producto->titulo_slug) }}">{{ $producto->titulo }}</a></h5>
<div class="listing__item__text__rating">
<span>{{ number_format($producto->km,0,',','.') }} km</span>
<h6>{{ number_format($producto->precio_contado,0,',','.' ) }} €</h6>
</div>
<ul>
<li><i class="fa fa-map-marker"></i> {{ $producto->municipio }}, {{ $producto->municipio_slug }}</li>
</ul>
</div>
</div>
</div>
@endforeach
No hay productos
{{ $productos->links() }}
App/Http/Comtrollers/FrontController
`<?php
namespace App\Http\Controllers;
use App\Models\Front;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Producto;
use App\Models\Link;
use Illuminate\Support\Facades\Session;
use App;
class FrontController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function anuncios()
{
return view('front.anuncios');
}
public function index()
{
return view('front.index');
}
public function detalle($titulo_slug)
{
// dd($titulo_slug);
if($titulo_slug !='index' && $titulo_slug !='blog'){
$producto = Producto::where('titulo_slug',$titulo_slug)
->first();
$num = $producto->visitas;
$num ++;
$producto->visitas = $num ;
$producto->save();
return view('front.detalle')->with('producto',$producto);
}
}
public function locale($lang)
{
App::setlocale($lang);
session(['locale' => $lang]);
return view('front.index');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Front $front
* @return \Illuminate\Http\Response
*/
public function destroy(Front $front)
{
//
}
}
`
Hi,
in April 2020 I've made a project in Laravel 7 and this laravel-localized-routes v2.2.6
. Now in October I installed in a new computer the development project and composer install downloaded the same version but it was changed, it started making error when trying artisan route:cache
I have updated the libraries with composer update
and now with version 2.3.2
has the same issue:
Unable to prepare route [sitemap.xml] for serialization. Another route has already been assigned name [es.sitemap].
The route:list shows the route for ES locale twice so when caching routes, the second one crashes with this error.
I have removed the fix for #28 in the file laravel-localized-routes/src/Macros/LocalizedRoutesMacro.php
in line 31 and it worked.
My configuration file localized-routes.php has:
'supported-locales' => [
'en' => env('APP_URL_EN'),
'es' => env('APP_URL')
],
'omit_url_prefix_for_locale' => 'es',
'use_locale_middleware' => true,
'use_localizer' => false,
I don't know if I'm doing something wrong or maybe the fix didn't work for all cases.
Hello,
I am currently trying to use Route Model Binding specifically and in all my tests it is not working. It seems that the Route Model Binding (https://github.com/codezero-be/laravel-localized-routes#-route-model-binding) via model function happens too early in the process, well before setLocale
.
The examples from the GitHub repo don't seem to work. I tried it with the latest version. In the controller the correct language comes back (when I dump) only within the model binding function not.
Is there another option? I need to return the database with the locale within a route model bind combination.
Thanks for your help in advance.
Kind of surprised the only reference to this I can is here: funkjedi/composer-include-files#7
Given this composer.json:
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
"files": [
"tests/macros.php"
]
},
The tests/macros.php
file has stopped autoloading after installing this package and the 0.0.0/composer-include-files
dependency.
I understand this is not an issue with this package per se, just wondering whether anyone is aware of a workaround? Seems like something that would break plenty of Laravel app test suites where files are autoloaded.
I made an attempt at debugging the composer plugin but hit a brick wall as I have close to zero knowledge of how composer plugins actually work, and the plugin appears to be based on something copy and pasted from composer v1.
Hi there.
I am struggling to manage my issue. What I need is to have these routes available:
/contacts - for default english, /uk/contacts - for ukrainian, etc...
Maybe some hints?
Something between the Translate Routes and Route Parameters sections of the README is confusing me. I have several named routes, of the form
Route::get(Lang::uri('dashboard/listing/{listing}'), [ContractController::class, 'create'])->name('dashboard.listing.edit');
Which are translated in /resources/lang/nb/routes.php
as
'dashboard' => 'konto',
'dashboard/listing' => 'konto/annonse',
'dashboard/listing/{listing}' => 'konto/annonse/{listing}',
As well as /resources/lang/en/routes.php
with keys matching values. When I try to generate a link to a specific resource, using {{ route('dashboard.listing.edit', {listing: contract.id} ) }}
in Twig, it only works in English.
Specifically, it yields http://127.0.0.1:8000/en/account/listing/103
in English, but http://127.0.0.1:8000/konto/listing/103
in Norwegian.
What would I need to specify to ensure that the second level of the URL is translated as well?
For the website I'm working on, the vast majority of routes will be localized. All of the admin area routes are broken with localized routes except for the dashboard. For example, there is a /admin/images
route but whenever I visit it, I get logged out and redirected back to the login page.
None of the /admin/*
routes work at all.
This happens both when the locale prefix is present and when it's omitted.
Obviously this shouldn't happen. What can I do to get this working as normal?
On the navbar of my project I have the following button:
Expected behavior:
What is happening:
Hello,
I have an error or rather a problem when I use the translation of routes.
Indeed I have created my files routes.php in the language folders and I always have a 404 error.
Cordially
Is there any way to force locale prefix in the URL, because when i redirect to another page the language is set to default.
For example when i'm in https://example.com/en and i click on a link it redirects to https://example.com/blog in the default language, does the package have a functionality to look at the App Locale and force the prefix in the URL?
Hi...
I have the folowing supported locale array:
'supported-locales' => [
'en',
'pt',
'es',
],
And the following home blade view:
{{ Route::localizedUrl('en') }}<br>
{{ Route::localizedUrl('pt') }}<br>
{{ Route::localizedUrl('es') }}
When I get mysite.test I see:
https://mysite.test
https://mysite.test/pt
https://mysite.test/es
Everything ok, when I change my supported locale array to:
'supported-locales' => [
'en' => 'mysite.test',
'pt' => 'pt.mysite.test',
'es' => 'es.mysite.test',
],
And get mysite.test again I see:
https://video-site.test
https://video-site.test
https://video-site.test
Is it a package issue?
Amazing package, by the way...
Hi, thanks for great project.
I'm using Route::macro...
in AppServiceProviders to switch locale for current page with links like 'EN','DE','NL'. And it works great for static routes with translated parameters.
My question is how can i switch language and at the same time translate localized uri segment. For slugs i'm using cviebrock/eloquent-sluggable.
I'm trying to translate this uri:
site.com/en/products/en-product-title-slug
into this:
site.com/de/produkte/de-produkte-titel-slug
At the moment i'm getting this:
site.com/de/produkte/[ENGLISH SLUG]
,
site.com/nl/produkt/[ENGLISH SLUG]
etc.
I prefer a global solution for the entire project but open to all suggestions.
Hello, I suggest to implement Route::is()
and Route::has()
to check the current route.
Actually I did a workaround:
Route::is('login')
became Route::is(app()->getLocale() . '.login')
Route::has('register')
became Route::has(app()->getLocale() . '.register')
But this is no nice.
Thanks for your work
Add the ability to configure custom slugs values for locales, in addition to localized domains.
Maybe something in the lines of:
'supported-locales' => ['en', 'nl'],
'domains' => [
'en' => 'en.domain.test',
'nl' => 'nl.domain.test',
],
'slugs' => [
'en' => 'english',
'nl' => 'dutch',
],
If you don't add a slug for a locale, the locale itself can be used, so it is optional.
If you don't add a domain for a locale, the default app_url
be used, so it is optional.
I just wanted to state publicly that your project is SORELY needed in the Laravel international world!
Also, thanks for using my 0.0.0/composer-include-files project!
I do the entire installation according to the instructions, as a result, when going to any page, an error
Route [uk.route_name] not defined.
what could be wrong?
Hi @ivanvermeyen,
The Call to a member function parameters() on null
error message is returned when I enter a random URL in order to trigger a 404 error.
It seems that the Route::current
returns null and generate an error in the macro. Is this something you get too on your projects ?
$request->route()->getAction('localized-routes-locale')
return only "en". I want omit_url_prefix_for_locale
to remain null
and default value to "az". How to change? Please tell me the path to the source code.
However, it returns "en" when no country code is specified for that route and omit_url_prefix_for_locale
is null
.
omit_url_prefix_for_locale
carries two tasks. This must have been difficult for him. There must also be a parameter for "en" declared by default.
Congratulations for the project.
Hi, it's me again ✋
I wonder if there would be a solution to keep URL params when using Route::localizedUrl
?
Currently, /dummy?foo=bar
URL returns:
/en/dummy
/fr/dummy
Wouldn't be correct to keep the URL parameters in order to get:
/en/dummy?foo=bar
/fr/dummy?foo=bar
As URL params are not subject to translations, wouldn't it be something pretty simple to implement ?
Hi guys,
how get I find the current language of the page?
I have tried with this first Lang::getLocale() and then app()->getLocale() but both give me the default language instead of the selected. How can I solve this?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.