weaver
weaver

Reputation: 453

Concat two columns With laravel eloquent

I have 3 tables, 1. countries 2. states 3.citites

COUNTRIES contains id, name columns .

STATES contains id, name, country_id columns.

CITIES contains id, name, state_id.

I am accessing cities with hasManyThrough() relation.

Relation:

public function cities()
{
   return $this->hasManyThrough('App\Models\City','App\Models\State');
}

How i am fetching citeis:

$countryObj = Country::where('name','like',$country.'%')->first();
$cities =  $countryObj->cities->pluck('name');
return response()->json(['cities'=>$cities],200);

I want to concat cites with theirs respective countries. Like: Uk-London

Upvotes: 0

Views: 191

Answers (1)

Rwd
Rwd

Reputation: 35200

One way to do this would be to use map. You can pass the $countryObj in to it and then simply concatenate the strings together:

$countryObj = Country::where('name', 'like', $country . '%')->first();

$cities = $countryObj->cities->map(function ($city) use ($countryObj) {
    return $countryObj->name . '-' . $city->name;
});

return response()->json(['cities' => $cities], 200);

Upvotes: 2

Related Questions