Reputation: 11
I've just started a new project in Laravel. I want it to be multi-language, so some tables have a field for each language, like:
Continent
id
en (for English)
pt (for Portuguese)
es (for Spanish)
So that:
1 'America', 'América', 'America'
2 'Africa', 'África', 'África'
Similarly, I have a "Regions" table.
My Continent model already has:
public function regions() {
return $this->hasMany(Region::class);
}
My goal is to rename the columns at runtime, so that I can use "Continent->name" or "Region->name", instead of "Continent->en" and "Region->en".
So far, I can achieve results this way:
ContinentController@index
public function index() {
$lang = 'en';
$continents = DB::table('continents')->rightJoin('regions', 'continent_id', '=', 'continents.id')->select("continents.$lang AS continent_name", "regions.$lang AS region_name")->get();
return view('geo.continents.index', compact('continents'));
}
However, that brings me a table:
@section('content')
@foreach ($continents as $continent)
{{ $continent->region_name }} {{ $continent->continent_name }}
@endforeach
@endsection
Central America (America)
Caribbean (America)
North America (America)
South America (America)
I want to accomplish a similar result, but using the Eloquent style. Something like this:
$continents = Continent::select('continents.en AS name')->with('regions')->get();
So far, I can get the continent name as a "name" property. How do I get the region name as a "name" property like:
$continent->name; $region->name;
Upvotes: 1
Views: 113