Quintella Rosa
Quintella Rosa

Reputation: 11

How to retrieve a column with another name in many-to-one Eloquent relationship

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

Answers (1)

Erich
Erich

Reputation: 2616

You want to look into scopes.

// Continent.php

public function scopeRegion($query, $region)
{
        return $query->where('region', $region);
}

Then in your controller,

Continent::region('en')->get();

Upvotes: 1

Related Questions