2017-04-03 4 views
0

データベースからモデルを取得し、withステートメントを使用して余分な情報を含む配列に変換するにはどうすればよいですか?モデルを配列に変換してjsonとして返します

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

答えて

1

あなたはそれを簡単にするためにLaravelのコレクションヘルパーを使用することができます。

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

これは何について:

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

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

collect($product)->toArray() 

は、その後、あなたが行うことができるはず

サプライヤーになる必要がある場合製品の属性で、これを試すことができます:

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

return response()->json($productArr, 200); 
関連する問題