Laravel 4.1 one-to-one polymorphic relationships

Warning - Old content ahead!

This page has been marked as a legacy post. This means it's quite old (from 2014) and probably out of date. Take it with a grain of salt!

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:

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

The Page model would be:

<?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:

<?php
class FeaturedImage extends Eloquent {
	public function imageable()
	{
			return $this->morphTo();
	}
}

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

Spread the word

Share this article

Like this content?

Check out some of the apps that I've built!

Snipline

Command-line snippet manager for power users

View

Pinshard

Third party Pinboard.in app for iOS.

View

Rsyncinator

GUI for the rsync command

View

Comments