Laravel 4.1 one-to-one polymorphic relationships

Posted on Jan 20, 2014

Laravel 4.1 Laravel PHP Eloquent

To use one-to-one polymorphic relationships in Laravel 4.1 use the "morphOne" method in your models.

For example: I have two tables, pages and products. I want to be able to add one featured image to each of these.

The Product model would look like this:

1
2
3
4
5
6
<?php
class Product extends Eloquent {
	public function image() {
		return $this->morphOne('FeaturedImage', 'imageable');
	}
}

The Page model would be:

1
2
3
4
5
6
<?php
class Page extends Eloquent {
	public function image() {
		return $this->morphOne('FeaturedImage', 'imageable');
	}
}

For the FeaturedImage table you would need to columns imageable_id:integer and imageable_type.

Then in your FeaturedImage model you can have:

1
2
3
4
5
6
7
<?php
class FeaturedImage extends Eloquent {
	public function imageable()
	{
			return $this->morphTo();
	}
}

This will allow you to use polymorphism on one-to-one relationships

Like this article? Sign up to updates - no spam!