请教!如何用 for+foreach 优化 blade 模版

我现在的需求是要在首页展示7个栏目的数据,每个栏目6条,用tab的形式。
我现在实现了功能,可视感觉代码太臃肿了,想问问大神们怎么优化。

controller

.
.
.
$indextype_pc_1 = TestPsy::where('test_category_id',1)->isAlive()->paginate(6);
$indextype_pc_2 = TestPsy::where('test_category_id',2)->isAlive()->paginate(6);
$indextype_pc_3 = TestPsy::where('test_category_id',3)->isAlive()->paginate(6);
$indextype_pc_4 = TestPsy::where('test_category_id',4)->isAlive()->paginate(6);
$indextype_pc_5 = TestPsy::where('test_category_id',5)->isAlive()->paginate(6);
$indextype_pc_6 = TestPsy::where('test_category_id',6)->isAlive()->paginate(6);
$indextype_pc_7 = TestPsy::where('test_category_id',7)->isAlive()->paginate(6);
.
.
.

blade

<div class="tab-pane fade show active" id="pills-1">
    <div class="index-cate-inner d-flex flex-wrap">
    @foreach($indextype_pc_1 as $indexhot)
        <div class="index-cate-items d-flex">
            ...
        </div>
    @endforeach
    </div>
</div>

其中因为我要靠pills-x来区分tab,所以这个结构在页面里重复了7次,如果用for来循环,foreach里的参数又没有办法用变量,这个应该怎么优化呢?

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 4

controller

$data = [];
for ($i = 1; $i < 8; $i++) {
    $data[$i] = TestPsy::where('test_category_id', $i)->isAlive()->paginate(6);
}

blade

<div class="tab-pane fade show active" id="pills-1">
    <div class="index-cate-inner d-flex flex-wrap">
    @foreach($data[1] as $indexhot)
        <div class="index-cate-items d-flex">
            ...
        </div>
    @endforeach
    </div>
</div>
4年前 评论
wongvio (楼主) 4年前
Hanson (作者) 4年前

或者传 query 到 blade,因为没看见你的分页,姑且当做你不需要分页

controller

$query = TestPsy::query()->isAlive();

blade

<div class="tab-pane fade show active" id="pills-1">
    <div class="index-cate-inner d-flex flex-wrap">
    @foreach($query->where('test_category_id', 1)->get(6) as $indexhot)
        <div class="index-cate-items d-flex">
            ...
        </div>
    @endforeach
    </div>
</div>
4年前 评论
wongvio (楼主) 4年前
@for($i=1;$i<8;$i++)
<div class="tab-pane fade show active" id="pills-{{ $i }}">
    <div class="index-cate-inner d-flex flex-wrap">
      @foreach($query->where('test_category_id', $i)->paginate(6) as $indexhot)
      ...
      @endforeach
   </div>
</div>
@endfor

@Hanson 好奇怪,foreach里的东西只输出了一遍

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!