Laravel 11 for Beginners: Localization and Languages

Arlind Musliu Portrait
Arlind Musliu

January 20, 2024 · 4 min read · 116 views

Laravel Blogpost Image

2024 UPDATE - LARAVEL 11

We're excited to announce that we have updated all of our blog post examples to reflect the new Laravel 11 version! Our previous examples were based on Laravel 10, but with the release of Laravel 11, we wanted to ensure that our readers have access to the most up-to-date information and examples.

Building Multilingual Apps for Global Reach

Your audience might come from different corners of the globe. To reach a wider audience and make your application more accessible, you'll want to present content in multiple languages. Laravel's localization features allow you to easily translate text and manage language files, making your app multilingual.

Understanding Laravel Localization

Localization in Laravel involves two main aspects: language files and translation functions. Language files are where you store translation strings, and translation functions are used to retrieve these strings within your application.

Language Files

Laravel stores language files within the lang directory. Within this directory, there should be a subdirectory for each language supported by your blog, such as en for English or es for Spanish. However, you won't find this directory before publishing those files.

Let's publish the files with the following command:

php artisan lang:publish

Here's an example of what a language file might look like:

<?php

return [
    'welcome' => 'Welcome to Our Blog',
    'latest_posts' => 'Latest Posts',
    // Other translation strings
];

As for the translation, you should create a similar file in the other language folder and change the translations.

Translation Functions

To use these translation strings in your application, Laravel provides the __() helper function. You can pass the key of the translation string you want to display, echo __('messages.welcome'); .

This function will automatically use the appropriate language file based on the user's language preference.

Setting the Locale

You can specify the default locale in the config/app.php file, 'locale' => 'en', .

To change the locale at runtime, you can use the App facade, App::setLocale('es'); .

You might want to determine the locale dynamically, perhaps based on the user's preference or browser settings.

Changing Localization through Blade

Step 1: Create an Invokable Controller

We already explained invokable controllers, now let's generate an invokable controller using the command:

php artisan make:controller LocaleController --invokable

Step 2: Implement the Locale Change

In the generated LocaleController, inside the __invoke method we should handle the locale change:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;

class LocaleController extends Controller
{
    public function __invoke(Request $request)
    {
        $locale = $request->input('locale');

        if (in_array($locale, ['en', 'es', 'sq'])) {
            Session::put('locale', $locale);
            App::setLocale($locale);
        }

        return redirect()->back();
    }
}

Step 3: Update the Route

Modify the route in your routes/web.php file to use the invokable controller:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
use App\Http\Controllers\LocaleController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::post('/locale', LocaleController::class)->name('locale.change');

Since the controller only contains a single action, you don't need to specify the method when defining the route. Laravel will automatically resolve and call the __invoke method.

Step 4: Creating a Language Switcher in Blade

In your Blade template, create a dropdown form that lets users switch the application's locale:

{{-- resources/views/layouts/app.blade.php --}}

<form action="{{ route('locale.change') }}" method="POST">
    @csrf
    <select name="locale" onchange="this.form.submit()">
        <option value="en"{{ app()->getLocale() == 'en' ? ' selected' : '' }}>English</option>
        <option value="es"{{ app()->getLocale() == 'es' ? ' selected' : '' }}>Español</option>
		<option value="sq"{{ app()->getLocale() == 'sq' ? ' selected' : '' }}>Shqip</option>
        <!-- Additional language options -->
    </select>
</form>

Step 4: Middleware for Applying the Locale

Create a middleware that checks the session for the locale and sets it accordingly:

php artisan make:middleware LocaleMiddleware

This will create a middleware LocaleMiddleware in the app/http/middleware folder. In the handle method of the middleware, apply the locale from the session:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;
use Symfony\Component\HttpFoundation\Response;

class LocaleMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle($request, Closure $next)
    {
        $locale = Session::get('locale') ?? 'en';
        Session::put('locale', $locale);
        App::setLocale($locale);

        return $next($request);
    }
}

Register the middleware in bootstrap/app.php:

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(append:[
            \App\Http\Middleware\LocaleMiddleware::class,
        ]);

        $middleware->alias([
            'check.author' => \App\Http\Middleware\CheckAuthorStatus::class,
        ]);
    })
    ->withEvents(discover: [
        __DIR__.'/../app/Domain/Listeners',
    ])
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Done! Feel free to switch between different languages.

Pluralization

Laravel also supports pluralization, which is a way to change the translation string based on a number. Here's an example of a pluralization string in a language file. Let's open the same translation file we had before, lang/en/messages.php:

<?php

return [
    'welcome' => 'Welcome to Our Blog',
    'latest_posts' => 'Latest Posts',
	'remaining' => '{0} No remaining posts|[1,*] :count remaining posts',
    // Other translation strings
];

And you can use it in your application like so:

<div>
  <h1>
	{{ trans_choice('messages.remaining', $count, ['count' => $count]) }}
  </h1>
</div>

Conclusion

Localization is a powerful feature in Laravel that helps make your application more inclusive and user-friendly for a global audience. By leveraging language files and translation functions, you can present your content in multiple languages, enhancing the user experience for readers around the world.

Upcoming Articles in the Series

  1. Laravel for Beginners: Query Performance Issues and Debugbar


Bring Your Ideas to Life 🚀

If you need help with a Laravel project let's get in touch.

Lucky Media is proud to be recognized as a Top Laravel Development Agency

Arlind Musliu Portrait
Arlind Musliu

Cofounder and CFO of Lucky Media

Technologies:

Laravel
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!