1

I am building a multi language app with Laravel, and I need the users to be able to log in and select their preferred language(table "languages") from a select field and store in the database("language_id" in table "users") just by selecting it from the field. I have currently no idea how I can achieve this without a form and a submit button. Can somebody explain to me how I can properly do this?

Controller: All available languages are stored in a variable and send to all views.

namespace App\Http\Controllers;

use App\Language;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\View;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;


    public function __construct()
    {
        $languages = Language::all();

        View::share('languages', $languages);
    }

}

Menu select: A foreach loop that populates the select field with the languages send via the controller.

                <li>

                        <select class="form-control" id="language" name="language">
                            @foreach ($languages as $language)
                                <option value="{{ $language->id }}">{{ $language->name }}</option>
                            @endforeach
                        </select>
                </li>

Database: "users" table has "language_id"

Izzy
  • 197
  • 3
  • 16

3 Answers3

2

I suppose user logged-in and you show one of the language as default language. After that try some thing like:

Jquery:

$('#language').change(function(){
    // make an ajax call and save the selected language option 
    // in the user table under the `language_id` column
    // and change the language of pages when selection changed
});

on each login fetch the value of language_id and according to that value show the selected language option. You can also keep that value in session to manage the dropdown state in entire application.

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
2

You have to save that data somewhere. In some cookie or session. If you want to manage it in Laravel I suggest to use AJAX call so that you will be able to handle it inside your app. Eather save it in the session or in a cookie.

Other way is to write it in cookie with javascript than read that same cookie when you load the page in some middleware and set the language.

In both cases you will need middleware to set the language every time a user load the page.

Community
  • 1
  • 1
melanholly
  • 762
  • 1
  • 9
  • 20
1

Here is the brief idea that how can you do that:

On change event of the select box, fire an AJAX call and store the value into the database table.

Let me know if you don't know how to code it. Can give you brief code.

Parth Vora
  • 4,073
  • 7
  • 36
  • 59