To achieve the desired output, you can use Laravel's Eloquent relationships to join the tables and retrieve the required data. Here's an example code snippet:
function getCityStateCountry()
{
$cityStateCountry = City::with(['state.country'])
->orderBy('name')
->get()
->map(function ($city) {
return $city->name . ', ' . $city->state->name . ', ' . $city->state->country->name;
})
->implode(', ');
return $cityStateCountry;
}
In this code, we're using the with method to eager load the related state and country models. Then, we're using the map method to format the data as required. Finally, we're using the implode method to join the formatted data with commas.
Note that this code assumes that you have defined the appropriate relationships in your City, State, and Country models. For example, in your City model, you would define a state relationship like this:
public function state()
{
return $this->belongsTo(State::class);
}
Similarly, in your State model, you would define a country relationship like this:
public function country()
{
return $this->belongsTo(Country::class);
}