Laravel: Returning the namespaced owner of a polymorphic relation

There are 2 easy ways – one below, other one in @lukasgeiter’s answer as proposed by Taylor Otwell, which I definitely suggest checking as well:

// app/config/app.php or anywhere you like
'aliases' => [
    ...
    'MorphOrder' => 'Some\Namespace\Order',
    'MorphStaff' => 'Maybe\Another\Namespace\Staff',
    ...
]

// Staff model
protected $morphClass="MorphStaff";

// Order model
protected $morphClass="MorphOrder";

done:

$photo = Photo::find(5);
$photo->imageable_type; // MorphOrder
$photo->imageable; // Some\Namespace\Order

$anotherPhoto = Photo::find(10);
$anotherPhoto->imageable_type; // MorphStaff
$anotherPhoto->imageable; // Maybe\Another\Namespace\Staff

I wouldn’t use real class names (Order and Staff) to avoid possible duplicates. There’s very little chance that something would be called MorphXxxx so it’s pretty secure.

This is better than storing namespaces (I don’t mind the looks in the db, however it would be inconvenient in case you change something – say instead of App\Models\User use Cartalyst\Sentinel\User etc) because all you need is to swap the implementation through aliases config.

However there is also downside – you won’t know, what the model is, by just checking the db – in case it matters to you.

Leave a Comment