I am making a bilingual app. I am using same routes for each but I am using different views for both languages. Whenever I want to redirect to a route I want to pass {{ route('test.route', 'en') }}
. Where I am passing en
, I want to fetch the current locale value from the view and then pass it to the route. Please help.
Laravel's localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application. Laravel provides two ways to manage translation strings. First, language strings may be stored in files within the lang directory.
Laravel-lang is a collection of over 68 language translations for Laravel by developer Fred Delrieu (caouecs), including authentication, pagination, passwords, and validation rules. This package also includes JSON files for many languages.
First you set $availableLangs the array of the available languages in your app, you may use config\app. php instead of initializing the array in the middleware as I did. If the first language is available in the request language data, it sets the locale, if not, it will search the next one, and so on.
try this. It will give the locale set in your application
Config::get('app.locale')
Edit:
To use this in blade, use like the following, to echo your current locale in blade.
{{ Config::get('app.locale') }}
If you want to do a if condition in blade around it, it will become,
@if ( Config::get('app.locale') == 'en')
{{ 'Current Language is English' }}
@elseif ( Config::get('app.locale') == 'ru' )
{{ 'Current Language is Russian' }}
@endif
To get current locale,
app()->getLocale()
At first create a locale route and controller :
Route::get('/locale/{lang}', 'LocaleController@setLocale')->name('locale');
class LocaleController extends Controller
{
public function setLocale($locale)
{
if (array_key_exists($locale, Config::get('languages')))
{
Session::put('app_locale', $locale);
}
return redirect()->back();
}
}
Now you can check easily in every page:
$locale = app()->getLocale();
$version = $locale == 'en' ? $locale . 'English' : 'Bangla';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With