Laravel 5 Localization(trans helper) tutorial example

By Hardik Savani | April 9, 2016 | | 20396 Viewer | Category : Laravel


First Laravel 5 introduce localization for laravel application. Localization is very pretty intrsting topic added on laravel 5. Localization through we can manage multiple language message. i mean you can manage multiple languages within your application. for example you have one title like "Home Page", this is static title and now it is in english, but you also manage other language like if this site open in spanish then name will like : "Página de inicio".

Laravel-Localization-Tutorial.png

So, laravel 5 provide to multi language messages stoare in file. you can do it easily using "trans" helper. you can do in your laravel application easily because laravel provide file in resources/lang.

In resources/lang directory have diffrence folder for various languages, you can create new folder for you own language. i am going to give you simple example for localization. so first create resources/lang/en/messages.php and put bellow code in that file.

resources/lang/en/messages.php

return [

'title' => 'Home Page Title - English',

'heading' => 'Home Page Heading - English',

];

Ok, now we did create messages.php file for english langauge, this file is use for retrieve english language message. now we can add over own language messages using create new folder. so i am going to create "es" folder for spanish language message. so, let's create new "es" folder in resources/lang. now first create resources/lang/es/messages.php and put bellow code in that file.

resources/lang/es/messages.php

return [

'title' => 'Home Page Title - Spanish',

'heading' => 'Home Page Heading - Spanish',

];

Ok, now we are ready to use trans helper in view, route or controller file every where you want. now i am going to give you example in view file.

welcome.blade.php

@extends('layouts.app')


@section('content')

<div class="row">

<div class="col-md-8">

<h1 class="text-primary" >{{ trans('messages.heading') }}</h1>

<?php App::setLocale('es'); ?>

<h1 class="text-primary" >{{ trans('messages.heading') }}</h1>

</div>

</div>

@endsection

In above example you can i use "App::setLocale" this facade function through we can define run time language. so in output you can see first english and then spanish message.

You can also define default language "spanish" by change app.php. If you want to change then open config/app.php and give locale = language folder name. You can also set "fallback_locale" language message. fallback_locale means if you have no message on current set language then it will take by default take from this language. you can see bellow configration.

config/app.php

[

.....

'locale' => 'en',

......

'fallback_locale' => 'en',

.....

]

So, let's start to implement on your laravel application, it is really good one...



Do you want to expert php developer or developer team for your projects ?
Contact US