LoginSignup
16
14

More than 3 years have passed since last update.

Laravelでfindしたレコードから特定のカラムを抽出したい

Last updated at Posted at 2019-07-25

例えばid==1のデータが欲しくて,かつその中でも特定のカラムのデータのみを抽出したかったが、方法がなかなか見つからなくて困ったのでメモしておく.

例えばProductというモデルがあり,そのテーブルには['id','title','description','price','created_at','updated_at']というカラムが存在しているとする.
ここで['title','description','price']のデータのみが欲しい際は以下のようにする.


\App\Product::find(1,['title','description','price']);

上記で特定の3カラムのデータのみを取り出せる.

例えばroutes/api.phpにおいて,上記の特定カラムのデータのみをJSONとしてresponseに出力するサンプルコードは以下の通り.


Route::get('products/{product_id}', function ($product_id) {
    $product = \App\Product::find(1,['title','description','price']);
    return response()->json($product);
});

7/26追記

コメント欄にて以下のような方法もあることを教えていただきました!
@yamatoxさん、ありがとうございます!


Route::get('/test1', function () {
    $product = \App\Product::select(['title','description','price'])->where('id', 1)->first();
    return response()->json($product);
});

{"title":"TEST","description":"DESCRIPTION","price":"1000"}

複数件取得(返り値はLaravelのCollectionクラス)

Route::get('/test2', function () {
    $products = \App\Product::select(['title','description','price'])->whereIn('id', [1,2])->get();
    return response()->json($products);
});
[
  {"title":"TEST","description":"DESCRIPTION","price":"1000"}, 
  {"title":"TEST2","description":"DESCRIPTION2","price":"2000"}
]

まとめ

なかなか真に迫る回答が見つけられなくて困った...
ちなみにfind()で帰ってくるのはEloquentインスタンスです.query()とかだとcollectionsインスタンスが返ってくるらしい.
クエリビルダあたりも勉強していきたいですね.

16
14
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
14