add-multilanguage-to-laravel

How Integrated Multi-language in Laravel -11

How Integrated Multi-language in Laravel -11

First we need to run a command to publish language in laravel

php artisan lang:publish

after that a folder named lang show on the root of the project directory

lang-on-root

Now we need to add some different Language in app.php

‘available_locales’ => [
‘English’ => ‘en’,
‘Russian’ => ‘ru’,
‘French’ => ‘fr’,
],

Now we have to create some common variable for different language

create en, fr, hi, ru files with .json extention and add below

for en.json
{
“thought_title”: “Thougt Of The Day”,
“thought_desc”: “Success is not final, failure is not fatal: It is the courage to continue that counts.”
}
for hi.json
{
“thought_title”: “आज का विचार”,
“thought_desc”: “सफलता अंतिम नहीं है, विफलता घातक नहीं है: यह जारी रखने का साहस है जो मायने रखता है।”
}for fr.json
{
“thought_title”: “Pensée du jour”,
“thought_desc”: “Le succès n’est pas définitif, l’échec n’est pas fatal : c’est le courage de continuer qui compte.”
}for ru.json
{
“thought_title”: “Мысль дня”,
“thought_desc”: “Успех не окончателен, неудача не фатальна: важна смелость продолжать.”}

Now we have to add a route in web.php

Route::get(‘language/{locale}’, function ($locale) {
app()->setLocale($locale);
$cookie = Cookie::make(‘locale’, $locale, 60 * 24 * 30); // Store the cookie for 30 days
return redirect()->back()->withCookie($cookie);
});

 Create a middleware and add below code to this

public function handle(Request $request, Closure $next)
{
if (Cookie::get(‘locale’)) {
App::setLocale(Cookie::get(‘locale’));
}
return $next($request);
}

Add this middleware to kernel.php

add-middleware-to-kernal

Create a partial-component resources/views/partials/language_switcher.blade.php

<select name=”language” id=”language” class=”form-select”>
    @foreach ($available_locales as $locale_name => $available_locale)
        <option value=”{{ $available_locale }}” @if ($available_locale === $current_locale) selected @endif>{{ $locale_name }}
        </option>
    @endforeach
</select>
<script>
    $(‘#language’).on(‘change’, () => {
        var language_val = $(‘#language’).val();
        var base_url = ‘{{ url(‘/’) }}’;
        var language_change_url = base_url + ‘/language/’ + language_val; // Construct the new URL
        window.location.href = language_change_url;
    });
</script>

Add this component to main file welcome.blade

<!doctype html>
<html lang=”en”>
<head>
    <!– Required meta tags –>
    <meta charset=”utf-8″>
    <meta name=”viewport” content=”width=device-width, initial-scale=1″>
    <!– Bootstrap CSS –>
    <link href=”https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css” rel=”stylesheet”
        integrity=”sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC” crossorigin=”anonymous”>
    <title>Multilanguage</title>
    <script src=”https://code.jquery.com/jquery-3.7.1.js” integrity=”sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=”
        crossorigin=”anonymous”></script>
</head>
<body>
    <nav class=”navbar navbar-expand-lg navbar-dark bg-dark”>
        <div class=”container-fluid”>
            <a class=”navbar-brand” href=”#”>Foodieland</a>
            <button class=”navbar-toggler” type=”button” data-bs-toggle=”collapse”
                data-bs-target=”#navbarSupportedContent” aria-controls=”navbarSupportedContent” aria-expanded=”false”
                aria-label=”Toggle navigation”>
                <span class=”navbar-toggler-icon”></span>
            </button>
            <div class=”collapse navbar-collapse” id=”navbarSupportedContent”>
                <ul class=”navbar-nav me-auto mb-2 mb-lg-0 “>
                    <li class=”nav-item”>
                        <a class=”nav-link active” aria-current=”page” href=”#”>Home</a>
                    </li>
                </ul>
                <form class=”d-flex”>
                    @include(‘partials/language_switcher’)
                </form>
            </div>
        </div>
    </nav>
    <main class=”container”>
        <div class=”bg-light p-5 rounded mt-3″>
            <h1>{{ __(‘thought_title’) }}</h1>
            <p class=”lead”>{{ __(‘thought_desc’) }}</p>
        </div>
    </main>
    <script src=”https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js”
        integrity=”sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM” crossorigin=”anonymous”>
    </script>
</body>
</html>

Add below code to app/Providers/AppServiceProvider.php

 public function boot()
    {
        view()->composer(‘partials.language_switcher’, function ($view) {
            $view->with(‘current_locale’, app()->getLocale());
            $view->with(‘available_locales’, config(‘app.available_locales’));
        });
    }

Run the code and see output in french and hindi

multilanguage-output

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *