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

Laravel如何从对象组成的集合查询数据并返回原生JSON

Laravel集合查询+返回JSON解决方案

1. 修正现有代码语法错误

你现有两段代码存在语法缺漏,先修正为正确写法:

集合定义修正

return collect([
    new Aligator('1', 'name1'),
    new Aligator('2', 'name2'),
    new Aligator('3', 'name3')
]);

路由定义修正

Route::get('/aligator/{name}', [AligatorController::class, 'getAligator']);

2. 配置Aligator类序列化规则

需要确保Aligator类的属性可被序列化为JSON,分两种情况:

  • 自定义普通类:将要返回的属性设为public
    class Aligator
    {
        public $id;
        public $name;
    
        public function __construct($id, $name)
        {
            $this->id = $id;
            $this->name = $name;
        }
    }
    
  • 继承Laravel Model的类:在类中声明可见字段
    class Aligator extends Model
    {
        // 允许序列化返回的字段
        protected $visible = ['id', 'name'];
    }
    

3. 实现控制器查询逻辑

在AligatorController中编写getAligator方法:

<?php
namespace App\Http\Controllers;

// 替换为你自己的Aligator类命名空间
use App\Aligator;
use Illuminate\Http\Response;

class AligatorController extends Controller
{
    // 封装集合获取逻辑,也可以直接写在查询方法内
    private function aligatorCollection()
    {
        return collect([
            new Aligator('1', 'name1'),
            new Aligator('2', 'name2'),
            new Aligator('3', 'name3')
        ]);
    }

    public function getAligator($name)
    {
        // 按name匹配集合中对应数据
        $target = $this->aligatorCollection()->firstWhere('name', $name);
        
        // 匹配不到返回404
        if (empty($target)) {
            return response()->json(['msg' => '数据不存在'], Response::HTTP_NOT_FOUND);
        }

        // 直接返回即可,Laravel默认会输出未格式化的压缩JSON
        // 如有不转义中文等需求,可加JSON_UNESCAPED_UNICODE参数
        return response()->json($target, Response::HTTP_OK, [], JSON_UNESCAPED_UNICODE);
    }
}

4. 验证效果

访问/aligator/name1即可得到对应Aligator对象的未格式化JSON数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:36:03