user7489552
user7489552

Reputation:

Display all Items using for loop - laravel php

I am able to fetch all names of the city belonging to the country being selected, but my issue lies with displaying all the cities in a label form. This is how my output looks like:

output

["Barcelona","Atlanta"]

How can i make the output look this way:

Barcelona

Atlanta

HTML

@foreach($countries as $country)
   <div class="panel">  
       {!!$country->city()->pluck('name');!!}             
   </div>
@endforeach

PS: New with laravel!

Upvotes: 0

Views: 261

Answers (2)

Thomas Van der Veen
Thomas Van der Veen

Reputation: 3226

You can access properties of your model just by using arrows. This would look like:

$country->city->name

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163788

It looks like each country has many cities, so to avoid N+1 problem, load the data first using with() method:

$countries = Country::with('cities')->get();

Make sure the relationship is hasMany:

public function cities()
{
    return $this->hasMany(City::class);
}

Then iterate over collection to display each city name:

@foreach($countries as $country)
    <div class="panel">
        @foreach ($country->cities as $city)
            {{ $city->name }}
        @endforeach            
    </div>
@endforeach

Upvotes: 1

Related Questions