Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Multilingual features in Laravel

In today’s interconnected world, businesses can no longer view customers as belonging solely to one nation or Language. To truly serve the needs of all, companies must build experiences that seamlessly bridge cultural divides.

At Hybrid Web Agency, we understand the importance of meeting users wherever they are – regardless of their mother tongue. It is our goal to foster connection and understanding across communities through inclusive digital tools.

This technical brief shares our framework for empowering dynamic Localization within web applications. By leveraging open-source technologies like Laravel, programmers can enable intuitive, personalized interfaces that welcome global audiences.

Within these pages, you will discover an optimization approach focused on a fluid, scalable infrastructure, and streamlined content management. Our solution considers the full customer journey from personalized routing to database structures.

It has been our privilege to develop solutions promoting accessibility and cultural exchange. We hope the techniques described here will help expand the reach and impact of your own ventures. Together, through sensitive engineering, we can build a more united digital landscape.

Laying the Groundwork

The first step is to install the Laravel framework along with the required packages. From the command line, run composer create-project laravel/laravel project-name to generate a new Laravel project.

Install additional packages like laravel/UI for authentication scaffolding and spatie/laravel-translation-loader to manage translations. Define their providers in config/app.php.

Update .env with database credentials and other secrets before migrating models and seeds. Configure a public disk for asset storage in config/filesystems.php.

Building Authentication

Authentication provides user context for localization. Generate an auth scaffold via Php Artisan ui:auth which installs Login/Register views and User model.

Configure web and API routes to leverage Passport for password and token authentication:

Route::middleware('auth:api')->group(function () {

// Routes requiring authentication

});

The default User migration defines id, name, etc fields. Add a language_code text column for the preferred language:

Schema::table('users', function (Blueprint $table) {

$table->string('language_code')->nullable(); 

});

Database Structure

Other than Users, define translation data models and migrations:

Schema::create('translations', function (Blueprint $table) {

$table->id();

$table->string('locale')->index();

$table->string('group');

$table->text('key'); 

$table->text('value');

});

This normalized structure separates language, keys, and values flexibly supporting multiple locales. Seed sample data to test localization.

Tying It Together

These foundational components provide authentication handling, data modeling, and seed data necessary to build out the localization features. Subsequent sections will integrate retrieval and display of translated content.

Storing Translated Content

Laravel provides tools for efficiently managing multilingual content across the application. The first step is to configure localization services.

Configuring Laravel localization

The first step is to configure Laravel’s localization functionality. Open the config/app.php file and update the ‘locale’ and ‘fallback_locale’ options:

'locale' => 'en',

'fallback_locale' => 'en',

Also, define the translator to use the localization loader:

'translator' => 'Spatie\TranslationLoader\Translator',

Creating translation files

Translation strings are stored in language group files within the resources/lang/ directory.

For example, create an en/pagination.php file:

// resources/lang/en/pagination.php

return [

'previous' => 'Previous',

'next' => 'Next'

];

Adding content to translation files

Additional languages can then be supported by duplicating the files:

// resources/lang/es/pagination.php

Translate the keys to Spanish within this new file.

Retrieving translations in views

Translations can now be accessed anywhere using the __ helper function:

{{ __('pagination.previous') }}

This will retrieve the string from the matching language file based on the app locale setting.

Setting User Language

Next up is the most important step

Adding language field to a User model

Open the User model and add a new string property for the preferred language:

// App/Models/User.php

class User extends Authenticatable

{

// ...

public $language;

}

Building language switcher

Create a dropdown in the navigation to allow selecting the language:

// resources/views/partials/nav.blade.php

Passing selected language to the app

Update the lang routine to save to the user:

// app/Http/Controllers/LangController.php

public function setLang(Request $request) 

{

$request->user()->language = $request->language;

$request->user()->save();

app()->setLocale($request->language);

}

Now the selected language persists for each user.

Dynamic URLs & Routing

Generating clean localized URLs requires prefixing routes with the language code and grouping common routes together.

Generating language-prefixed routes

Prefix router groups with the locale parameter:

Route::prefix('{locale}')->group(function() {

Route::get('products', 'ProductController@index');

});

Creating route group for language prefix

The language code can be extracted from the prefix:

$locale = Route::current()->parameter('locale');

Re-direct to default when locale missing.

Linking between languages

Generate internal links with the current locale:

URL()->current(); 

URL()->current().'/products;

External links include locale switch:

url()->toRoute($route,$params,[

'locale' => 'es'

]);

Now content and navigation dynamically adjust based on the routed locale parameter. Clean localized URLs tie the experience together.

Displaying Content

Once the infrastructure is in place, content can be dynamically retrieved and output based on the user’s language.

Retrieving content based on language

Use the __ helper to translate strings:

{{ __('messages.welcome') }}

Load localized content from database based on App::getLocale():

php

Copy

$page = Pages::where('lang', $locale)->find($id);

Displaying images/strings conditionally

Conditionally output images/text based on language:

@if($locale == 'es')



@else



@endif

Processing forms and input based on language

Translate form labels and validation messages:

'name.required' => __('validation.required', ['attribute' => 'Name']),

Localize date/number formatting:

{{ $date->formatLocalized('%d-%m-%Y') }}

The views and controllers can now fetch and display dynamic, localized content depending on the visitor’s preferred language.

Testing & Deployment

Once development is complete, thorough testing ensures translations work as expected before deploying to production.

Testing translation functionality

Create test routes to test translation loading from sample files:

Route::get('translation/{key}', function($key){

return __($key);

});

Validate UI renders published resources correctly in all languages.

Publishing translations to GitHub/storage

Publish translation files for version control:

php artisan vendor:publish --tag=translations

Commit updated language files to source control on GitHub.

Deploying to server

Bundle assets for production:

npm run production

php artisan optimize

Publish translations, migrate database, and compile JS/CSS on server:

php artisan migrate

php artisan config:cache

Load testing to verify expected behavior at high volumes. Continuously monitor and accept localized user feedback.

Rigorous testing delivers confidence in quality and performance as the solution serves a global audience on production servers.

Conclusion

Building multilingual applications requires laying a flexible foundation that empowers delivering customized experiences to diverse users worldwide. The techniques discussed here illustrate how Laravel facilitates the complexities of localization through thoughtful database structures, configuration options, and helper functions.

By separating data from presentation, the normalized translation tables allow seamless addition of languages without code changes. Meanwhile, locale-aware routing ensures language remains contextual throughout each user’s journey. Together, these fundamentals provide the scaffolding to serve personalized content at a global scale.

Most importantly, the goal of any technical approach should be connecting all people regardless of language or location. As the web brings more of the world together, considerate engineering plays a role in creating a welcoming digital landscape that values inclusion over exclusion.

While technical challenges remain in scaling localization features, each implementation expanding accessibility takes us closer to realizing the internet’s potential as a true platform for cultural exchange. May the approaches shared here help more projects deliver understanding across boundaries through respectful and available design.



This post first appeared on The Ultimate Guide To Affordable Custom Website Development Services For Small Businesses, please read the originial post: here

Share the post

Multilingual features in Laravel

×

Subscribe to The Ultimate Guide To Affordable Custom Website Development Services For Small Businesses

Get updates delivered right to your inbox!

Thank you for your subscription

×