Laravel Language Option

By ukmodak | March 31st 2024 10:38:02 AM | viewed 812 times

Run the following command in order to create the required middleware

   D:\xampp_726\htdocs\bazar> php artisan make:middleware Localization

Then open it. The file should be in "bazar/app/Http/Middleware/Localization.php and update the following code:

public function handle($request, Closure $next)
{
   if(\Session::has('locale'))
   {
       \App::setlocale(\Session::get('locale'));
   }
   return $next($request);
}

Lets say you want your website to be in English and French.

    Go to "bazar/resources/lang/en/"

    Create a file name "messages.php"

    Create folder "fr" in "bazar/resources/lang/"

    Create a file name "messages.php" in "bazar/resources/lang/fr/"

Open "messages.php" in en folder and insert the following codes.

return [
    'welcome'=> 'Welcome to our application'
];

Open "messages.php" in fr folder and insert the following codes.

return [
    'welcome'       => 'Bienvenue sur notre application'
];

Add the below codes in "bazar/app/Http/Kernel.php" in "protected $middlewareGroups section".

\App\Http\Middleware\Localization::class,

Now add following code in the route, "bazar/routes/web.php" on top of other defined routes.

Route::get('locale/{locale}', function ($locale){
    Session::put('locale', $locale);
    return redirect()->back();
});

Add this in the page template


To change the language, just create an anchor tag in html like the following :

<li><a href="{{ url('locale/en') }}" ><i class="fa fa-language"> EN</a></li>
<li><a href="{{ url('locale/fr') }}" ><i class="fa fa-language"> FR</a></li>
bONEandALL
Visitor

Total : 26654

Today :3

Today Visit Country :

  • France
  • United States