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

Laravel 4.2:如何将Eloquent模型get()结果转换为指定数组格式?

解决Laravel 4.2 Eloquent结果转指定格式的问题

Hey there! I’ve messed around with Laravel 4.2 enough to know this feeling—you grab results with ->get() and suddenly you need to shape them into something specific, but you’re not sure where to start. Let’s fix this step by step.

First, let’s clarify: when you call ->get() on an Eloquent query, you get a Laravel Collection object, not a plain array or JSON. That’s good news because Collections have tons of built-in methods to transform your data.

1. Quick, built-in format conversions

If you just need a basic array or JSON, these one-liners work perfectly:

// Convert Collection to a plain PHP array
$resultsArray = YourModel::where('some_condition', true)->get()->toArray();

// Convert directly to JSON string
$resultsJson = YourModel::where('some_condition', true)->get()->toJson();

2. Customize the format with map()

For more control—like renaming fields, combining values, or filtering data—use the map() method to iterate over each item in the Collection:

$formattedResults = YourModel::get()->map(function($item) {
    return [
        'custom_id' => $item->id,
        'full_title' => $item->title . ' (' . $item->category . ')',
        'formatted_date' => $item->created_at->format('M d, Y')
    ];
});

// If you need the final result as an array, chain ->toArray()
$finalArray = $formattedResults->toArray();

3. Define a default format in your Model

If you always want a specific structure when converting this model to an array/JSON, override the toArray() method directly in your Eloquent model:

// app/models/YourModel.php
class YourModel extends Eloquent {
    public function toArray() {
        return [
            'id' => $this->id,
            'display_name' => $this->name,
            'last_updated' => $this->updated_at->timestamp
        ];
    }
}

// Now whenever you call ->toArray() or ->toJson(), it uses this structure
$formatted = YourModel::get()->toArray();

4. Bonus: Pick only the fields you need

If you don’t want all model attributes, you can select specific fields in your query first to reduce extra data:

$trimmedResults = YourModel::select('id', 'name', 'created_at')->get()->toArray();

Keywords to search for more help

If you need to dive deeper, these terms will point you in the right direction:

  • Laravel 4.2 Eloquent Collection transform
  • Laravel 4.2 model toArray customize
  • Laravel 4.2 map Collection format
  • Laravel 4.2 Eloquent convert to custom array

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:24:57