phplaravellaravel-localization

Localization not working in laravel 8 with json file


I am trying to implement multiple languages in my laravel application with json files in resource/lang/ directory with shortnames of languages i.e en.json, ar.json. Following is the code

web.php

Route::get('lang/{lang}', [HomeController::class,'switchLang'])->name('lang');

HomeController.php

public function switchLang($lang)
    {
        App::setLocale($lang);
        \Artisan::call('config:clear');
        \Artisan::call('config:cache');
        \Artisan::call('cache:clear');
        return redirect()->back();
    }

**Note: ** I have also tried through middleware by protecting all the routes using following middleware

Language.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class Language
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next,$lang)
    {
        App::setLocale($lang);
        \Artisan::call('config:clear');
        \Artisan::call('config:cache');
        \Artisan::call('cache:clear');
        return $next($request);
    }
}

Solution

  • don't do artisan calls when the user change language.

    setLocale should be enough, but you need to store that locale in the session at least,

    switchLang :

    session()->put('locale', $lang);
    

    middleware:

    if(session()->has('locale')) {
        app()->setLocale(session()->get('locale'));
    }
    

    a better option could be to store it in the users table