I have a base Message
class for an inbox using a polymorphic relationship to attach custom message types which all implement the same interface and behave differently in views based on their type. Display of that all works swimmingly, but I hit a snag when I tried to actually add these with code.
This is the Message class:
<?php
class Message extends Eloquent {
public function author() {
$this->belongsTo("User", "author_id");
}
public function recipient() {
$this->belongsTo("User", "recipient_id");
}
public function message() {
$this->morphTo();
}
}
The model that I attach to message()
implements MessageInterface
, So I thought I'd be able to make a quick helper to attach this model's relationship via Message::send()
:
public static function send(MessageInterface $message, User $to, User $from) {
if (! $message->exists)
$message->save();
$parent = new static;
$parent->author()->associate($from);
$parent->recipient()->associate($to);
$parent->message()->associate($message); // line that errors
return $parent->save();
}
But this ends up throwing what looks to be infinite recursion at me:
FatalErrorException: Maximum function nesting level of '100' reached, aborting!
This is the studly
function, and from some searching it seems to happen when two models reference each other.
The Schema for the messages table is:
$table->increments("id");
$table->integer("message_id")->unsigned();
$table->string("message_type");
$table->integer("recipient_id")->unsigned();
$table->integer("author_id")->unsigned();
$table->timestamps();
Am I just doing something really wrong, here? I've looked through the morphTo
method call in the source and tried seeing if reflection is the problem here (grabbing the function name and snake casing it), but I can't seem to find what is happening. The associate method call is just setting attributes and getting the class name for message_type
, then returning a relationship.
There's no useful information in the error; it's a Symfony\Component\Debug\Exception\FatalErrorException
with no context.
I'm running Laravel 4.1