将模型转换为数组并返回为json

时间:2017-04-03 23:20:00

标签: php laravel laravel-5

如何从数据库中获取模型,然后使用with语句将其转换为包含额外信息的数组。

public function edit($id) {
    // convert product to array;
    $product = Product::findOrFail($id)->with('supplier', 'category');

    $data = [
        'suppliers' => Supplier::all()->pluck('company', 'id'),
    ];        

    // cannot merge because $product is object and cannot turn into array
    // the only way I know to convert to array is doing this
    // $product->first()->toArray() but this gets the first item in the database
    $product = array_merge($product, $data);

    return response()->json($product, 200, ['Content-Length' => strlen(json_encode($product))]);
}

2 个答案:

答案 0 :(得分:1)

您可以使用Laravel的集合助手来简化:

collect($product)->toArray()

然后你应该能够做到:

$product array_merge(collect($product)->toArray(), $data);

答案 1 :(得分:0)

这个怎么样:

$return = [
    'suppliers' => Supplier::all()->pluck('company', 'id'),
    'product' => $product // or $product->toArray()
];

return response()->json($return, 200);

如果您需要供应商作为产品的属性,您可以尝试:

$productArr = $product->toArray();
$productArr['suppliers'] = Supplier::all()->pluck('company', 'id');

return response()->json($productArr, 200);