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

如何从数据库中获取模型,然后使用WITH语句将其转换为Array,包括额外的信息?

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))]);
}

You could use Laravel's collection helper to make it simple:

collect($product)->toArray()

Then you should be able to do:

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

What about this:

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

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

If you need the suppliers to be an attribute of the product, you could try this:

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

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