How can I get the lang inside my controller in laravel

Viewed 2988

I am sending a post request to a controller with axios. The languge is set to fr and all blade texts are also changed to fr but if I send a post request using axios it doesn't translate from the controller. I tried to see the language in the controller and it always shows en.

Here is the code I am using..

Initial route to load the login blade

Route::get('/{lang?}/login', 'Auth\LoginController@showLoginForm')->name('login');

This route inside a middleware which set the lang according to the lang variable.

Post request using axios

Route::post('user/login', [
   'uses' => 'loginController@login'
 ]);

Inside loginController@login

$loc=config('app.locale');
\Log::info($loc); // It always shows en

And I am trying to return the translated text like this

return response()->json([
      'error' => trans('Invalid Details') // I am using string as key in fr.json file
 ],401);

**I think trans function is not working for me not even in my blade where in blade @lang('key') and {{__(key')}} work just fine but not the trans function **

Do I have to set the locale in every routes whether it is an ajax request or plain get request? Because I set the locale when the page was loaded initially so do I have to do it again for ajax requests too?

Thank you.

1 Answers

If you want to set local inside your controller,

function showLoginForm($language){
    app()->setLocale($language);
    ........
    ........
}

If you want to set local for all sub route, then try following one

// set locale for '/admin/anything/[en|fr|ru|jp]/anything' only
if (in_array(Request::segment(1),['en', 'fr', 'ru', 'jp'])) {
    App::setLocale(Request::segment(1));
} else {
    // set default / fallback locale
    App::setLocale('en');
}

Route::group(['prefix' => '{locale}'], function() {
    Route::resource('product', 'ProductController', ['except' => [
    'show'
    ]]);
});
Related