laravelmiddleware

Undefined array key "default_language"


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);
    }
}

Solution

  • 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