How to fetch current locale in view in Laravel 5.3 - laravel

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.

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';

Related

Attempt to read property "degree" on null

i have created a profile where users can add their education fields.
when there is no value in the database it throws an error. how can i get rid of this ? Attempt to read property "degree" on null.
public function myEducations()
{
return $this->hasMany('App\Models\Education','user_id')->orderByDesc('endDate');
}
controller
public function myProfile(\App\Models\User $user)
{
$user = Auth::user();
$education = $user->myEducations->first();
return view('candidate.profile',compact('user','education'));
blade
{{ $education->degree }} - {{ $education->fieldOfStudy }}
If the users of you application are filling in their education details later only. You should ideally catch this condition when rendering your view. For example you could try the following:
#if ($education)
{{ $education->degree }} - {{ $education->fieldOfStudy }}
#else
<p>Education details not available</p>
#endif
You have to inspect in an if statement $education->degree is not null.
If not null, degree has value, this part will render.
Else, it doesn't have value so else block appears in template.
#if(null !== $education->degree)
{{ $education->degree }} - {{ $education->fieldOfStudy }}
#else
// there is no degree
#endif

Set global variable / text direction in Laravel middleware

I have a middleware that reads the language setting from the database and applies the sets the application locale accordingly:
public function handle($request, Closure $next)
{
$lang = SystemSetting::find('System Language');
\App::setLocale($lang->value);
return $next($request);
}
I would also like to set the text direction (rtl or ltr) so it will be available to my blade template in order to load the necessary css files.
I can easily do it in the controller but i do not wish to repeat it in every controller and pass it to the view for every page in my application. Is there a way to set a global variable or something similar so I can do this in my blade template:
#if ($RTL)
{{ Html::style('css/rtl/app-rtl.css') }}
#else
{{ Html::style('css/app.css') }}
#endif
You can use the view facade, that you can read more about here.
This allows you to directly prepare any data for the views and make it available there.
<?php
use Illuminate\Support\Facades\View;
public function handle($request, Closure $next)
{
$lang = SystemSetting::find('System Language');
\App::setLocale($lang->value);
View::share('rtl', true);
return $next($request);
}
But I would suggest looking into flashing this into the session.
You can change with translation
<html lang="{{config('app.locale')}}" dir="{{#trans('interface.dir')}}">
interface in ar file :
return [
//add this line in ar file
'dir' =>'rtl',
]
interface in en file :
return [
//add this line in en file
'dir' =>'ltr',
]

Laravel - Passing Parameters/ undefined variable

I'm struggling with passing parameters through in Laravel, I can access it via URL but I don't want that. I'm getting Undefined variable: user in the master.blade error.
Any help is appreciated
AuthController.php
function viewUserDetails($userId)
{
$user = User::find($userId);
return view('user/userdetails',['user' => $user]);
}
Web.php
Route::get('userdetails/{userId}', 'AuthController#viewUserDetails');
Master.Blade
<li>Your Details</li>
Other guys are telling you about userdetails view, but your code is totally fine. What you need to do is pass $user variable to the master view too:
return view('master', ['user' => $user]);
Try to pass like this
return view('user/userdetails')->with('user' => $user);
Controller::
function viewUserDetails($userId)
{
$user = User::find($userId);
return view('user.userdetails')-with('user',$user);
}
Then Used In blade File..
#foreach ($user as $data){
<h1> {{ $data['_id'] }} </h1>
<h1> {{ $data['name'] }} </h1>
#endforeach
I assume that you have extended master.blade in user/userdetails.blade. You need use array as second parameter to url function.
<li>Your Details</li>
It is best practice to use named route in laravel.
Change your route like this :
Route::get('userdetails/{userId}', 'AuthController#viewUserDetails')->named('user_details');
In your blade you can use route function to get the path.
<li>Your Details</li>
You can update your code like:
AuthController.php
function viewUserDetails($userId)
{
$user = User::find($userId);
return view('user.userdetails',compact('user'));
}
Web.php
Route::get('userdetails/{userId}', 'AuthController#viewUserDetails');
Master.Blade
<li>Your Details</li>

Laravel 5.x: How to replace locale in URL in view/blade?

I've a blade in my views, which looks like this:
#if (App::getLocale() == 'de')
<a href="/en/dashboard">
<i class="fa fa-language">ENGLISH</i>
</a>
#elseif (App::getLocale() == 'en')
<a href="/de/dashboard">
<i class="fa fa-language">GERMAN</i>
</a>
#endif
This creates a button, which allows me to switch to the other language.
Well... The URL could also be one of these:
/en/settings
/en/logbook
I want, that the button redirects to the same page, but on a different language:
/en/dashboard -> /de/dashboard
/en/settings -> /de/settings
/en/logbook -> /de/logbook
Using {{ Request::url() }} I'm able to get the current URL, but what's now the best way / solution to use this URL just with a different locale?
{{ Request::url() }} for example contains /en/dashboard and I would now need /de/dashboard.
Does there any Laravel function exist or do I need to code this with PHP within... The blade?
I have wrote this small helper function about 2 years ago. It works great when you pass $locale variable and it adds it to URL's first segment.
public static function getLocaleChangerURL($locale){
$uri = $_SERVER['REQUEST_URI'];
$uri = explode('/', $uri);
unset($uri[0]);
unset($uri[1]);
$url = url($locale);
foreach($uri as $u){
$url .= '/'.$u;
}
return $url;
}
I would prefer this way.
public static function getLocaleChangerURL($locale)
{
$uri = request()->segments();
$uri[0] = $locale;
return implode($uri, '/');
}

Eloquent: get related model with aliases

I have a view where a related model property gets displayed.
{{ $product->category->title_en }}
I'd rather put this like
{{ $product->category->title }}
And make the locale selection in my controller.
For example with the main model:
View:
{{ $product->title }}
Controller:
if ($locale === 'en') {
$product = Product::where(id of something)->get([
'title_en AS title'
])
}
How can I set aliases for the related?
Or is there a better option?
I've created a helper function for this for my own project. As the locale is the first in all urls, I explode it and use it like this.
function translate($model, $column)
{
$url = explode('/', Request::path());
return $model[$column . '_' . $url[0]];
}
In the view file, I use:
{{ translate($product, 'title') }}
Alternatively you can use App::getLocale() to get the current locale.
you can use select() but you have to write names of other columns too in select()
if ($locale === 'en') {
$product = Product::where(id of something)
->select('title_en as title','col2','col3'....)
->get()
}

Resources