4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Laravel】配列からEloquentモデルを生成する(newInstanceとhydrate)

Last updated at Posted at 2019-06-12

この記事は移行しました!最新の内容はこちらをご覧ください😀

やりたいこと

DBに保存せずに配列をEloquentモデルにしたい。

例)Itemモデルにしたい

単一のとき

$item = [
    "name" => "商品A",
    "price" => "100",
];

普通にnewする

new Item($item);

ただしテスト書きづらくなるのでオススメしない。

newInstanceを使う

Item::make()->newInstance($item);

※makeでいいのかわかってない。。makeはItemがインスタンス化されている場合は不要。

複数のとき

$items = [];
$item = [
    "name" => "商品A",
    "price" => "100",
];
$items[] = $item;
$item = [
    "name" => "商品B",
    "price" => "200",
];
$items[] = $item;

hydrateを使う

Item::hydrate($items);

返り値はCollectionになる。

4
4
0

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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?