douzhao7445 2017-10-27 09:55
浏览 28
已采纳

使用for循环显示所有项目 - 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!

  • 写回答

2条回答 默认 最新

  • dongmoxin7111 2017-10-27 09:58
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)