1666309680
Easy i18n localization for Laravel, an useful tool to combine with Laravel localization classes.
The package offers the following:
Laravel | laravel-localization |
---|---|
4.0.x | 0.13.x |
4.1.x | 0.13.x |
4.2.x | 0.15.x |
5.0.x/5.1.x | 1.0.x |
5.2.x-5.4.x (PHP 7 not required) | 1.2.x |
5.2.x-5.8.x (PHP 7 required) | 1.3.x |
5.2.0-6.x (PHP 7 required) | 1.4.x |
5.2.0-9.x (PHP 7 required) | 1.7.x |
Install the package via composer: composer require mcamara/laravel-localization
For Laravel 5.4 and below it necessary to register the service provider.
In order to edit the default configuration you may execute:
php artisan vendor:publish --provider="Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider"
After that, config/laravellocalization.php
will be created.
The configuration options are:
You may register the package middleware in the app/Http/Kernel.php
file:
<?php namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
/**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [
/**** OTHER MIDDLEWARE ****/
'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
'localeCookieRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleCookieRedirect::class,
'localeViewPath' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationViewPath::class
];
}
Add the following to your routes file:
// routes/web.php
Route::group(['prefix' => LaravelLocalization::setLocale()], function()
{
/** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
Route::get('/', function()
{
return View::make('hello');
});
Route::get('test',function(){
return View::make('test');
});
});
/** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/
Once this route group is added to the routes file, a user can access all locales added into supportedLocales
(en
and es
by default). For example, the above route file creates the following addresses:
// Set application language to English
http://url-to-laravel/en
http://url-to-laravel/en/test
// Set application language to Spanish
http://url-to-laravel/es
http://url-to-laravel/es/test
// Set application language to English or Spanish (depending on browsers default locales)
// if nothing found set to default locale
http://url-to-laravel
http://url-to-laravel/test
The package sets your application locale App::getLocale()
according to your url. The locale may then be used for Laravel's localization features.
You may add middleware to your group like this:
Route::group(
[
'prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ]
], function(){ //...
});
1.: It is strongly recommended to use a redirecting middleware. Urls without locale should only be used to determine browser/default locale and to redirect to the localized url. Otherwise, when search engine robots crawl for example http://url-to-laravel/test
they may get different language content for each visit. Also having multiple urls for the same content creates a SEO duplicate-content issue.
2.: It is strongly recommended to localize your links, even if you use a redirect middleware. Otherwise, you will cause at least one redirect each time a user clicks on a link. Also, any action url from a post form must be localized, to prevent that it gets redirected to a get request.
The following redirection middleware depends on the settings of hideDefaultLocaleInURL
and useAcceptLanguageHeader
in config/laravellocalization.php
:
Whenever a locale is present in the url, it will be stored in the session by this middleware.
If there is no locale present in the url, then this middleware will check the following
useAcceptLanguageHeader
is set to true, compute locale from browser and redirect to url with locale.hideDefaultLocaleInURL
is set to true.For example, if a user navigates to http://url-to-laravel/test and en
is the current locale, it would redirect him automatically to http://url-to-laravel/en/test.
Similar to LocaleSessionRedirect, but it stores value in a cookie instead of a session.
Whenever a locale is present in the url, it will be stored in the cookie by this middleware.
In there is no locale present in the url, then this middleware will check the following
useAcceptLanguageHeader
is set to true, compute locale from browser and redirect to url with locale.hideDefaultLocaleInURL
is set to true.For example, if a user navigates to http://url-to-laravel/test and de
is the current locale, it would redirect him automatically to http://url-to-laravel/de/test.
When the default locale is present in the url and hideDefaultLocaleInURL
is set to true, then the middleware redirects to the url without locale.
For example, if es
is the default locale, then http://url-to-laravel/es/test would be redirected to http://url-to-laravel/test and theApp::getLocale()
would be set to es
.
This package comes with a bunch of helpers.
Localized URLS taken into account route model binding when generating the localized route, aswell as the hideDefaultLocaleInURL
and Translated Routes settings.
// If current locale is Spanish, it returns `/es/test`
<a href="{{ LaravelLocalization::localizeUrl('/test') }}">@lang('Follow this link')</a>
Get current URL in specific locale:
// Returns current url with English locale.
{{ LaravelLocalization::getLocalizedURL('en') }}
Returns a URL clean of any localization.
// Returns /about
{{ LaravelLocalization::getNonLocalizedURL('/es/about') }}
Returns a route, localized to the desired locale. If the translation key does not exist in the locale given, this function will return false.
// Returns /es/acerca
{{ LaravelLocalization::getURLFromRouteNameTranslated('es', 'routes.about') }}
Return all supported locales and their properties as an array.
{{ LaravelLocalization::getSupportedLocales() }}
Return all supported locales but in the order specified in the configuration file. You can use this function to print locales in the language selector.
{{ LaravelLocalization::getLocalesOrder() }}
Return an array with all the keys for the supported locales.
{{ LaravelLocalization::getSupportedLanguagesKeys() }}
Return the key of the current locale.
{{ LaravelLocalization::getCurrentLocale() }}
Return current locale's name as string (English/Spanish/Arabic/ ..etc).
{{ LaravelLocalization::getCurrentLocaleName() }}
Return current locale's native name as string (English/Español/عربى/ ..etc).
{{ LaravelLocalization::getCurrentLocaleNative() }}
Return current locale's direction as string (ltr/rtl).
{{ LaravelLocalization::getCurrentLocaleDirection() }}
Return the ISO 15924 code for the current locale script as a string; "Latn", "Cyrl", "Arab", etc.
{{ LaravelLocalization::getCurrentLocaleScript() }}
Register the middleware LaravelLocalizationViewPath
to set current locale as view-base-path.
Now you can wrap your views in language-based folders like the translation files.
resources/views/en/
, resources/views/fr
, ...
As you can modify the supportedLocales even by renaming their keys, it is possible to use the string uk
instead of en-GB
to provide custom lang url segments. Of course, you need to prevent any collisions with already existing keys and should stick to the convention as long as possible. But if you are using such a custom key, you have to store your mapping to the localesMapping
array. This localesMapping
is needed to enable the LanguageNegotiator to correctly assign the desired locales based on HTTP Accept Language Header. Here is a quick example how to map HTTP Accept Language Header 'en-GB' to url segment 'uk':
// config/laravellocalization.php
'localesMapping' => [
'en-GB' => 'uk'
],
After that http://url-to-laravel/en-GB/a/b/c
becomes http://url-to-laravel/uk/a/b/c
.
LaravelLocalization::getLocalizedURL('en-GB', 'a/b/c'); // http://url-to-laravel/uk/a/b/c
LaravelLocalization::getLocalizedURL('uk', 'a/b/c'); // http://url-to-laravel/uk/a/b/c
If you're 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.
<ul>
@foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
<li>
<a rel="alternate" hreflang="{{ $localeCode }}" href="{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], true) }}">
{{ $properties['native'] }}
</a>
</li>
@endforeach
</ul>
Here default language will be forced in getLocalizedURL() to be present in the URL even hideDefaultLocaleInURL = true
.
Note that Route Model Binding is supported.
You may translate your routes. For example, http://url/en/about and http://url/es/acerca (acerca is about in spanish) or http://url/en/article/important-article and http://url/es/articulo/important-article (article is articulo in spanish) would be redirected to the same controller/view as follows:
It is necessary that at least the localize
middleware in loaded in your Route::group
middleware (See installation instruction).
For each language, add a routes.php
into resources/lang/**/routes.php
folder. The file contains an array with all translatable routes. For example, like this:
<?php
// resources/lang/en/routes.php
return [
"about" => "about",
"article" => "article/{article}",
];
<?php
// resources/lang/es/routes.php
return [
"about" => "acerca",
"article" => "articulo/{article}",
];
You may add the routes in routes/web.php
like this:
Route::group(['prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localize' ]], function () {
Route::get(LaravelLocalization::transRoute('routes.about'), function () {
return view('about');
});
Route::get(LaravelLocalization::transRoute('routes.article'), function (\App\Article $article) {
return $article;
});
//,...
});
Once files are saved, you can access http://url/en/about , http://url/es/acerca , http://url/en/article/important-article and http://url/es/articulo/important-article without any problem.
Maybe you noticed in the previous example the English slug in the Spanish url:
http://url/es/articulo/important-article
It is possible to have translated slugs, for example like this:
http://url/en/article/important-change
http://url/es/articulo/cambio-importante
However, in order to do this, each article must have many slugs (one for each locale). Its up to you how you want to implement this relation. The only requirement for translatable route parameters is, that the relevant model implements the interface LocalizedUrlRoutable
.
To implement \Mcamara\LaravelLocalization\Interfaces\LocalizedUrlRoutable
, one has to create the function getLocalizedRouteKey($locale)
, which must return for a given locale the translated slug. In the above example, inside the model article, getLocalizedRouteKey('en')
should return important-change
and getLocalizedRouteKey('es')
should return cambio-importante
.
To use route-model-binding, one should overwrite the function resolveRouteBinding($slug)
in the model. The function should return the model that belongs to the translated slug $slug
. For example:
public function resolveRouteBinding($slug)
{
return static::findByLocalizedSlug($slug)->first() ?? abort(404);
}
You may want to checkout this video which demonstrates how one may set up translatable route parameters.
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:
Event::listen('routes.translation', function($locale, $attributes)
{
// Do your magic
return $attributes;
});
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
To cache your routes, use:
php artisan route:trans:cache
... instead of the normal route:cache
command. Using artisan route:cache
will not work correctly!
For the route caching solution to work, it is required to make a minor adjustment to your application route provision.
In your App's RouteServiceProvider
, use the LoadsTranslatedCachedRoutes
trait:
<?php
class RouteServiceProvider extends ServiceProvider
{
use \Mcamara\LaravelLocalization\Traits\LoadsTranslatedCachedRoutes;
For more details see here.
This may happen if you do not localize your action route that is inside your Routes::group
. This may cause a redirect, which then changes the post request into a get request. To prevent that, simply use the localize helper.
For example, if you use Auth::routes()
and put them into your Route::group
Then
<form action="/logout" method="POST">
<button>Logout</button>
</form>
will not work. Instead, one has to use
<form action="{{ \LaravelLocalization::localizeURL('/logout') }} " method="POST">
<button>Logout</button>
</form>
Another way to solve this is to put http method to config to 'laravellocalization.httpMethodsIgnored' to prevent of processing this type of requests
If you do not localize your post url and use a redirect middleware, then the post request gets redirected as a get request. If you have not defined such a get route, you will cause this exception.
To localize your post url see the example in POST is not working.
This also happens if you did not localize your post url. If you don't localize your post url, the default locale is set while validating, and when returning to back()
it shows the validation message in default locale.
To localize your post url see the example in POST is not working.
During the test setup, the called route is not yet known. This means no language can be set. When a request is made during a test, this results in a 404 - without the prefix set the localized route does not seem to exist.
To fix this, you can use this function to manually set the language prefix:
// TestCase.php
protected function refreshApplicationWithLocale($locale)
{
self::tearDown();
putenv(LaravelLocalization::ENV_ROUTE_KEY . '=' . $locale);
self::setUp();
}
protected function tearDown()
{
putenv(LaravelLocalization::ENV_ROUTE_KEY);
parent::tearDown();
}
// YourTest.php
public function testBasicTest()
{
$this->refreshApplicationWithLocale('en');
// Testing code
}
Ask mcamara if you want to be one of them!
View changelog here -> changelog
Author: mcamara
Source Code: https://github.com/mcamara/laravel-localization
License: MIT license
1625465520
In this example i will show you localization - laravel localization example.
Laravel’s localization features provide a convenient way to retrieve text in different languages, allowing you to easily support multiple languages within your application. So here i will show you how to create localization or laravel dynamic language.
#localization - laravel localization example #localization tutorial #localization #laravel multi languag #laravel documentation #laravel localization
1595201363
First thing, we will need a table and i am creating products table for this example. So run the following query to create table.
CREATE TABLE `products` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
Next, we will need to insert some dummy records in this table that will be deleted.
INSERT INTO `products` (`name`, `description`) VALUES
('Test product 1', 'Product description example1'),
('Test product 2', 'Product description example2'),
('Test product 3', 'Product description example3'),
('Test product 4', 'Product description example4'),
('Test product 5', 'Product description example5');
Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'name','description'
];
}
Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.
routes/web.php
Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);
#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete
1621508419
Hire our expert team of Laravel app developers for flexible PHP applications across various cloud service providers.
With this easy build technology, we develop feature-rich apps that make your complex business process a lot easier. Our apps are,
Get your business a best in classlaravel app. Hire laravel app developers in India. We have the best organizational set-up to provide you the most advanced app development services.
#laravel app development company india #hire laravel developers india #laravel app development company #hire laravel developers #laravel development agency #laravel app programmers
1670234150
In the present world, PHP is a well-liked framework. Laravel is one of the most well-known frameworks out there. The popularity of Laravel is due to its expressiveness, flexibility, good controllers, strength, seamless caching, and time savings when handling tasks like routing, authentication, sessions, and many more.
Laravel is a PHP framework that everyone who knows PHP should be familiar with. The Laravel PHP framework is simple to learn and use, but it is packed with useful features. Despite rising market competition, many developers consider Laravel to be one of the best PHP frameworks available.
WPWeb Infotech is a top Laravel development company in India and the US since 2015. They develop reliable, scalable Laravel web and mobile apps using Ajax-enabled widgets, MVC patterns, and built-in tools. WPWeb Infotech has top-notch expertise in combining a variety of front- and back-end technologies like Laravel + VueJS, Laravel + Angular, and Laravel + ReactJS to create scalable and secure web architectures, so you don't have to worry about scalability and flexibility while developing your product. They understand business scale and recommend technology that fits. Agile experts reduce web and mobile app development time and risk.
When it comes to hiring Laravel developers from India, they are the best choice because their Laravel developers can work according to your time zone to provide you with hassle-free, innovative, and straightforward web development solutions. Being the most trusted Laravel development company in India, they can help you reach new heights of success, unleashing the power of the Laravel PHP framework.
Partner with one of India’s best Laravel Development Company and get the most expertise in Laravel development.
#laravel #laravel-development #laravel-development-company #laravel-development-services #hire-laravel-developers
1625635800
Hello friends,
Today I will give you example of how to create multi language website in laravel. In this example or tutorial you can understand a concept of laravel multilingual website example demo. Also gain knowledge or learn about how to add multiple languages in laravel. it’s very simple example of laravel multi language with different list of language dropdown.
#how to create multi language website in laravel #laravel #laravel localization #laravel multiple language website #change website language dynamically in laravel #multilingual website