i am having this issue on my laravel app, am trying to implement change language middleware but i keep getting this error undefined array key. This is the middleware snippet
public function handle(Request $request, Closure $next): Response
{
$localeLanguage = \Session::get('languageChangeName');
$defaultLanguage = getSuperAdminSettingValue()['default_language']->value;
if (! isset($localeLanguage)) {
if(!empty($defaultLanguage)){
\App::setLocale($defaultLanguage);
$defaultLanguage;
}else{
\App::setLocale('en');
}
} else {
\App::setLocale($localeLanguage);
}
return $next($request);
}
}
That error has occurred because the supposed array being returned by the getSuperAdminSettingValue method does not contain "default_language" key as part of the data in the array. I would suggest you assign the response from the method to a variable on a seperate line and then dd it to check what is returned before continuing with the rest of the implementation.
$superAdminSettingValues = getSuperAdminSettingValue();
/*
* The line below is to be deleted before proceeding to the next line
* after confirming the variable is not an empty array and has the
* default_language as part of its data
*/
dd($superAdminSettingValues);
$defaultLanguage = $superAdminSettingValues['default_language']->value;
I would encourage you to read on Laravel Localization. It is used to handle situations such as this in your laravel project. It involves using the command
php artisan lang:publish
to publish the language files from laravel in your project and setting a default language for your app in the config/app.php file. After which, I would approach the code a little differently using the following steps
Publish the lang file with the command above
Set the default locale in the config/app.php file by assigning a value to the APP_LOCALE key. As such, we would always have a value for default locale except if the value is not set in the config file. Then my code will be like this
public function handle(Request $request, Closure $next): Response
{
/*
* Get the locale language set in the session provided it has been
* set earlier somewhere else.
*/
$localeLanguage = \Session::get('languageChangeName');
/*
* Get the current locale value i.e app default locale
*/
$currentLocale = \App::currentLocale();
if (isset($localeLanguage)) {
\App::setLocale($localeLanguage);
} else {
if (!isset($currentLocale)) {
\App::setLocale('en');
}
}
return $next($request);
}