LoginSignup
4
3

More than 3 years have passed since last update.

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

Posted at

やりたいこと

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