phplaravel-bladelaravel-5.8

Laravel change language via URL/Route


Fairly new to Laravel and I'm trying to add a functionality that allows the user to switch between two languages by clicking a button in a header.blade.php file. So far I've got it so there's a test.php file in the respective lang directories with test strings and have managed to get <p>{{__('test.test')}}</p> to display the correct language when manually set. At the moment I'm not sure if this is actually calling the route to update the language or if the logic I have for updating it is wrong since I get no errors and I'm using barryvdh/laravel-debugbar to debug.

My logic for the button:

<button href="{{ url('language', config('app.locale') == 'en' ? 'fr' : 'en') }}">{{ config('app.locale') }}</button>

In routes/web.php:

Route::get('/language', 'LanguageController@show');
Route::post('/language/{lang}', 'LanguageController@update');

LanguageController.php, created via php artisan make:controller --api

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class LanguageController extends Controller
{
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return App::getLocale();
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //Tried the following
        config(['app.locale' => $id]);
        App::setlocale($id);
    }
}

Questions:

  1. Is this the correct way to update the language at runtime?
  2. How can I tell if my api calls are being made?
  3. How can I achieve this inside of a template .vue file?
  4. Is making a Controller for the language redundant?
  5. Would the inner HTML of my button change if the locale was changed?
  6. Is affecting config files at runtime bad practice?

--Edit-- I should also mention that the only reason I made a controller for this is because I had the route calls in web.php use a function instead however, they stated they were Closure running php artisan route:list and with the research I found I couldn't tell if that was correct


Solution

  • You are on the right way, but there is something missing.

    You can't use the configuration to edit at runtime the language.

    Save local language in user Session and create a new middleware to set on each request the language saved in session.

    I found this article that can help you, localization-laravel