mardi 2 octobre 2018

A morphOne factory isn't working because the 'owner' fields aren't being set

So, I am trying to seed a table called 'address' which allows multiple models to have rows, so the schema is like so:

Schema::create('addresses', function (Blueprint $table) {
    $table->increments('id');
    $table->morphs('owner');
    $table->string('address');
    $table->string('city');
    $table->string('state');
    $table->string('postcode');
    $table->string('country');
    $table->string('latitude')->nullable();
    $table->string('longitude')->nullable();
    $table->timestamps();
});

The owner_id and owner_type are models that can have an address (they can only have one)

So, for this example, let's say I want to create a factory for my projects table

/**
 * Seed the application's database.
 *
 * @return void
 */
public function run()
{
    Model::unguard();

    $projects = factory(Project::class, 150)->create();

    // This throws an error 
    // owner_type doesnt have a default value
    $projects->each(function($project) {
        $project->address()->save(factory(Address::class)->make());
    });
}

My project.php relation for addresses is like so:

/**
 * @return \Illuminate\Database\Eloquent\Relations\MorphTo
 */
public function owner(): morphTo
{
    return $this->morphTo('owner');
}

My address factory is like so:

Address factory

$factory->define(App\Core\Entities\Address::class, function (Faker $faker) {
    return [
        'address'    => $faker->address,
        'city'       => $faker->city,
        'state'      => $faker->state,
        'postcode'   => $faker->postcode,
        'country'    => $faker->country,
        'latitude'   => $faker->latitude,
        'longitude'  => $faker->longitude,
    ];
});

Now, when I create an address in my controllers, I do it like so, which works (but obvioudly for factories I can't)

        $project = auth()->user()->projects()->save(new $this->project($request->validated()));

        $project->address()->save(new $this->address($request->validated()));

So my question is, why doesn't this work?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire