Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optional polymorphic relation results in fatal error #1450

Closed
schickling opened this issue May 29, 2013 · 9 comments
Closed

Optional polymorphic relation results in fatal error #1450

schickling opened this issue May 29, 2013 · 9 comments

Comments

@schickling
Copy link

At the moment if you use polymorphic relations there always has to be a relation, otherwise an error occurs PHP Fatal error: Class name must be a valid object or a string. Thats clear since the implementation of the morphTo method looks up for a class of type xy. If no such is provided it results in an error.

For "normal" relations if two models are allowed to be in a relation but they aren't thats fine. The same behavior would be nice for polymorphic relations.

Example (from docs):

class Photo extends Eloquent {

    public function imageable()
    {
        return $this->morphTo();
    }

}

class Staff extends Eloquent {

    public function photos()
    {
        return $this->morphMany('Photo', 'imageable');
    }

}

If a Photo would be not in a relationship with a Staff model and just "lives on his own", that should be possible two and not result in an error.

@greggilbert
Copy link
Contributor

+1. Got the same thing, only I'm using $this->morphOne() instead of morphMany.

@schickling
Copy link
Author

I'm glad to know I'm not the only one facing this issue!

@ShawnMcCool
Copy link

Yea, optimally this would return an empty collection.

@taylorotwell
Copy link
Member

I'm confused. What is happening? imagable should just return null, right? But you're saying it errors? Am I understanding that correctly?

@schickling
Copy link
Author

Yes. In case of morphOne it should return null, in case of morphMany it should return an empty collection.

@taylorotwell
Copy link
Member

Well the problem is really with morphTo right?

@schickling
Copy link
Author

Yeah, sorry my bad

@driesvancraen
Copy link

I'm having the same issue here.. Any solutions?

@ShawnMcCool
Copy link

This is just a fundamental part of morphTo(). You can't create the morphTo object without already having a direct mapping to the target model.

You can create a setter that does something like:

$model->setSubject($thread);

Which then does something like..

public function setSubject($subject)
{
    $this->subject_id = $subject->getKey();
    $this->subject_type = get_class($subject);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants