1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Basic Study LogAdvent Calendar 2024

Day 16

LaravelのmakeメソッドってDBに保存されないの?

Posted at

はじめに

Laravelでテストを書くときにmake()を使うのかcreate()を使うのかで曖昧だったので違いについて調べる。

makeメソッド

vendorを見にいくと、make()ではモデルのインスタンス作成のみを行っており、DBに保存する処理は行っていなかった。

vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factory.php
/*
 * Create an instance of the given model.
 *
 * @param  string  $class
 * @param  array  $attributes
 * @return mixed
 */
public function make($class, array $attributes = [])
{
    return $this->of($class)->make($attributes);
}

/*
 * Create a builder for the given model.
 *
 * @param  string  $class
 * @param  string  $name
 * @return \Illuminate\Database\Eloquent\FactoryBuilder
 */
public function of($class, $name = 'default')
{
    return new FactoryBuilder($class, $name, $this->definitions, $this->states, $this->faker);
}
vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php
/*
 * Create a collection of models.
 *
 * @param  array  $attributes
 * @return mixed
 */
public function make(array $attributes = [])
{
    if ($this->amount === null) {
        return $this->makeInstance($attributes);
    }

    if ($this->amount < 1) {
        return (new $this->class)->newCollection();
    }

    return (new $this->class)->newCollection(array_map(function () use ($attributes) {
        return $this->makeInstance($attributes);
    }, range(1, $this->amount)));
}

createメソッド

以下の記事の通り、create()では新しいモデルインスタンスを作成してデータベースに保存を行い、そのインスタンスを返す。

まとめ

  • create():DBにデータを保存してインスタンス作成を行う
  • make():DBにデータ保存をせず、インスタンス作成のみを行う
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?