Laravel Eloquent polymorphic one-to-one?

BenjaminRH picture BenjaminRH · Feb 25, 2014 · Viewed 9.6k times · Source

I'm trying to setup a polymorphic one-to-one relationship (the polymorphic equivalent of has_one and belongs_to).I've got an Address model, and there are several other models that I want to have one address. However, I'm confused by the wording of the docs. I've seen the morphMany method, but my question is: should I use morphMany even though I only want it to have one address, or is there something like a morphOne method I should be using?

EDIT: My Address model has these fields, just to help visualize:

Schema::create('addresses', function ($table)
{
    $table->increments('id');
    $table->string('street');
    $table->string('street_more')->nullable();
    $table->string('city');
    $table->string('state')->nullable();
    $table->string('country');
    $table->string('postal_code');
    $table->integer('addressable_id');
    $table->string('addressable_type');
});

Answer

marcanuy picture marcanuy · Feb 25, 2014

Yes, there is a morphOne method and I think is the one you should use in this case: https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L811 .

Also you can use

$table->morphs('addressable');

instead of

$table->integer('addressable_id');
$table->string('addressable_type');

I've used morphOne in a custom package for L4 and works pretty well.