You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中提取Country/Category/Region模型title字段生成可遍历数组的最优方法

嘿,这个需求在Laravel里处理起来很顺手,我给你分享几种最优的实现方式,你可以根据自己的场景来选:

方法一:Eloquent集合合并(最简洁高效)

Laravel的Eloquent集合自带merge()方法,配合pluck()可以快速提取并合并三个模型的title字段,这是最推荐的方式——pluck()只会查询title字段,避免不必要的数据加载,代码也足够清爽。

// 控制器代码
use App\Models\Country;
use App\Models\Category;
use App\Models\Region;

// 提取各模型的title并合并成集合,再转成数组
$titles = Country::pluck('title')
    ->merge(Category::pluck('title'))
    ->merge(Region::pluck('title'))
    ->toArray();

// 将变量传递到视图
return view('your-target-view', compact('titles'));

然后在视图里直接遍历即可:

{{-- 视图代码 --}}
@foreach($titles as $title)
    <div>{{ $title }}</div>
@endforeach

如果需要去除重复的title值,只需要在合并后加上->unique():

$titles = Country::pluck('title')
    ->merge(Category::pluck('title'))
    ->merge(Region::pluck('title'))
    ->unique() // 去重
    ->toArray();
方法二:单独处理后合并(适合需自定义前缀/格式的场景)

要是你需要给不同模型的title加上标识(比如区分“国家”“分类”“地区”),可以用map()方法单独处理每个集合,再用array_merge()合并:

// 控制器代码
$countryTitles = Country::pluck('title')->map(fn($title) => "国家:{$title}")->toArray();
$categoryTitles = Category::pluck('title')->map(fn($title) => "分类:{$title}")->toArray();
$regionTitles = Region::pluck('title')->map(fn($title) => "地区:{$title}")->toArray();

$titles = array_merge($countryTitles, $categoryTitles, $regionTitles);

return view('your-target-view', compact('titles'));
方法三:封装复用方法(多处使用时推荐)

如果这个需求在项目的多个地方都要用到,建议把逻辑封装成可复用的方法,避免重复代码。比如创建一个Helper类或者直接在模型里添加静态方法:

方式1:创建Helper函数

在app/Helpers/TitleHelper.php中定义:

<?php

use App\Models\Country;
use App\Models\Category;
use App\Models\Region;

function getAllModelTitles()
{
    return Country::pluck('title')
        ->merge(Category::pluck('title'))
        ->merge(Region::pluck('title'))
        ->unique()
        ->toArray();
}

记得在composer.json里自动加载这个Helper:

"autoload": {
    "files": [
        "app/Helpers/TitleHelper.php"
    ]
}

然后运行composer dump-autoload,之后就可以在控制器里直接调用:

$titles = getAllModelTitles();
return view('your-target-view', compact('titles'));

方式2:模型静态方法(可选)

也可以在其中一个模型或者单独的类里添加静态方法,比如:

// 在Country模型里
public static function getAllTitles()
{
    return self::pluck('title')
        ->merge(Category::pluck('title'))
        ->merge(Region::pluck('title'))
        ->unique()
        ->toArray();
}

然后控制器调用:

$titles = Country::getAllTitles();
return view('your-target-view', compact('titles'));

内容的提问来源于stack exchange,提问作者psudo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 14:34:11