Question

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');
});
Was it helpful?

Solution

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.

OTHER TIPS

Try this one, I think this is better than morphOne that not supported.

  public function address()
  {
      return $this->hasOne('App\Address', 'addressable_id','id')
                   ->where('addressable_type', 'App\Model');
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top