Search code examples
phplaravelmodelcontrollerlocale

How do I return data from different tables based on user's locale on Laravel


I have a multi-language website and what I want to do is displaying different content from different tables (lang_en, lang_es, lang_fr.. etc)

I've tried something like this: [*1]:

[*1]:

// ContentController.php

  public function content_bylang($id)
  {
    $table = 'lang_'.Config::get('app.locale'); // app.locale=["en", "es", ..]
    $data = \DB::table($table)->where('id', $id)->get();

    return view('content', ['data' => $data]);
  }




When I do it this way, it works but the way I do it really doesn't seem so effective.

Is there any other way for handling this kind of calls?

--

Things I can't do: I can't add each content inside the resources/lang/x.php file


Solution

  • if your many table has same column can use Model and override the Model's constructor

    parent::__construct();
    $this->table = 'lang_'.Config::get('app.locale');
    

    so next time in your controller only need to call the model without extra configuration and pass it to the view