Arabic-English Laravel App With Dynamic Style In 10 Steps

Posted in Web Development

Laravel supports a great technique to support multiple languages localization in your application. In this article, I’ll explain step by step how to do that simply and also changing styles dynamically from ltr or rtl depending on localization.

Let’s start smile

Step 1:

Before creating a new laravel project,make sure to install all dependencies .you can check this guide https://laravel.com/docs/5.6/installation to make sure that all dependencies are installed.

we will create a new laravel project. Open command prompt and cd your server path,here I use XAMPP so my server projects will be in htdocs folder.

Run this command

Your_server_path > laravel new "your_project_name"

 

After installing all packages,you can view the laravel app in browser using

way 1: Start the apache and then visit the following url: localhost/your_project_name

way 2: Use laravel internal server using this command

php artisan serve

 

then open the browser on the following url http://127.0.0.1:8000/ .you’ll see the default laravel app page.

laravel localization

Step 2:

Open resources->lang folder, you’ll find "en" folder by default installation of laravel.

Here we add our localization folders like fr,es,ar …..I’ll use Arabic language so created folder and named it "ar".Then create new php file and name it translation.php ,this file will return the corresponding Arabic translation if localization is set to "ar".Add this lines to it

return[

'title'=>'لارافل'      //title is the key //لارافل is value of key in arabic localization

];

 

Copy this file then paste it in "en" folder and change the value of title to "Laravel".

So our folder structure looks like this

resources

  ->en

      ->translation.php   

  ->ar

      ->translation.php

 

Step 3:

To make "laravel" title in default page is translated dynamically from localization folder,we’ll use laravel interpolation {{ __(filename.key)}} instead of static "Laravel" title.So Open resources->views->welcome.blade.php and replace this div

<div class="title m-b-md">
    Laravel //replace this with dynamic title return value 
</div>

 

with

  {{__('translation.title')}}      

 

Note:

translation is the file name in lang folder and title is the key value

Step 4:

Create new middleware which will be responsible for setting app localization.

Naviage to app->http->middleware,create new file and name it Localization.php

paste this code into it

namespace App\Http\Middleware;

use Closure;

use Carbon\Carbon;

use App;

use Config;

use Illuminate\Support\Facades\Session;

class Localization

{

public function __construct(App $app) {

    $this->app = $app;

}

/**

* Handle an incoming request.

*

* @param  \Illuminate\Http\Request  $request

* @param  \Closure $next

* @return mixed

*/

public function handle($request, Closure $next)

{

    if(Session::has('locale')){

        $current_locale= Session::get('locale');//get saved session locale value

        App::setLocale($current_locale); // set app localization with locale value session

        Carbon::setLocale($current_locale); //set carbon localization for date/time system with locale value session

    }

    else{

        $app_locale = session('locale', config('app.locale')); // set session locale with app localization setting & return the locale value

        Carbon::setLocale($app_locale);//set carbon localization with current app localization configuration

    }

    return $next($request);

}

 

Then register Localization middleware in app->http->kernel.php

Add the following line at the end of $middlewareGroups array like that

'web' => [

....

\App\Http\Middleware\Localization::class

]

 

Note:

config('app.locale') return the default configured setting value for locale key in config->app.php

Step 5:

By default,Laravel set locale to "en".But what if we want to set the default language for application with Arabic.

let's do it laughing

Open .env file and paste this lines at end of the file

APP_Languages='ar'   //the default language

Fallback_Languages='ar' //The fallback language determines the language to use when the current one is not available

 

Make locale key setting in config->app.php read its value from .env file like that

//'locale' => 'en',

'locale' => env('APP_Languages','ar'),

 

//'fallback_locale' => 'en',

'fallback_locale' => env('Fallback_Languages','ar'),

 

Now if you navigate to browser,you'll see that laravel title is translated to arabic

laravel localization

Step 6:

Now ,we set the localization of the app from .env file but let’s make it using button switcher in the front-end.Navigate to resources->views->welcome.blade.php and before closing head tag,import bootstrap css library like that

"https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

<link rel="stylesheet" href=
"https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

 

Also add bootstrap js library before closing body tag

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script
src=
"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>

 

After importing bootstrap css and js libraries,add dropdown button in place of div with class=”links”

<div class="dropdown">
    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Check Your Locale
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
        <a class="dropdown-item" href="#">English</a>
        <a class="dropdown-item" href="#">Arabic</a>
    </div>
</div>

 

Navigate to browser and refresh

laravel localization

Step 7:

Add the functionality of language switcher when click on English link then change app localization configuration to "en" also the Arabic link change app localization configuration to "ar" .we can do that by sending them as parameters for router and set locale configuration with this parameter.

Open routes->web.php and add this new route

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

Session::put('locale',$locale);

   return redirect()->back();

})->name('switchLan');  //add name to router

 

Open resources->views->welcome.blade.php and change href value with the new route

<a class="dropdown-item" href="{{route('switchLan','en')}}">English</a>
<a class="dropdown-item" href="{{route('switchLan','ar')}}">Arabic</a
>

 

Visit the browser and change localization using button switcher links smile

Step 8:

Now,we implemented localization well but need to change page style from rtl(right to left) or ltr(left to right) when localization changes.

Create two new css files in public->css and name it ltr-app.css for english localization & rtl-app.css for arabic localization.

Add this style to ltr-app.css

.title{

text-align: left;

}

 

Also for rtl-app.css

.title{

text-align:right;

}

.dropdown-menu.show {

text-align: right;

}

 

Step 9:

Open resources->views->welcome.blade.php and before closing head tag add this lines

@if(app()->getLocale() == 'en')
    <link rel="stylesheet" href="css/ltr-app.css">
    @else
    <link rel="stylesheet" href="css/rtl-app.css">
@endif

 

Note:

app()->getLocale() return current app localization if set to "en" then import ltr-app.css else will import rtl-app.css.also search about div with class =‘flex-center’ and remove this class to see the effect of text-align.

Step 10:

Before naviagating to browser to see the results,add this lines to resources->lang->ar-> translation.php

'btn'=>'اللغة',

'arabic'=>'العربية',

'english'=>'الإنجليزية'

 

Also add these lines to resources->lang->en->translation.php

'btn' => 'Language',

'arabic' => 'Arabic',

'english' => 'English'

 

Change dropdown div in welcome.blade.php to make it read from resources->lang folder using laravel interpolation like that

<div class="dropdown">
    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        {{__('translation.btn')}}
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
        <a class="dropdown-item" href="{{route('switchLan','en')}}"> {{__('translation.english')}}</a>
        <a class="dropdown-item" href="{{route('switchLan','ar')}}"> {{__('translation.arabic')}}</a>
    </div>
</div>

 

Now it’s time to see the final resultcool

laravel localization

For english language

laravel localizationConclusion

Laravel's localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application.You can read more about laravel's localization from this reference https://laravel.com/docs/5.6/localization Also you can access this project files from https://gitlab.com/ayamostafa/ar-en-laravel-localization if you clone this project, don’t forget to run "composer update" first before running it in the browsersmile

Comments


No Comments

- Please, Login to fully participate in discussion .

LEAVE A COMMENT

Cancel