0

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

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

What if i want to concat each cities with their country. Like: UK-London,US-New york,...
@weaver You could eager load the states and countries with the cities and then use map again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.