Laravel 4.2:如何将Eloquent模型get()结果转换为指定数组格式?
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 transformLaravel 4.2 model toArray customizeLaravel 4.2 map Collection formatLaravel 4.2 Eloquent convert to custom array
内容的提问来源于stack exchange,提问作者luca ditrimma

