Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

milroy's avatar

Polymorphic Relations gives Class 'Staff' not found

When I try to retriever data through a morphTo() funnction it throwa a FatalErrorException. Class 'XXX' not found.

0 likes
6 replies
pmall's avatar

You should use the full namespace of the class in the relationship definition

bobbybouwmann's avatar

For example you do this

class Order extends Model {

    public function tickets()
    {
        return $this->morphMany('App\Photo', 'ticketable');
    }

}
milroy's avatar
class Photo extends Model{

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

}

class Staff extends Model{

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

}

class Order extends Model{

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

}

All three classes under App namespace. When I try

Photo::find(1)->imageable();

It throwa a FatalErrorException. Class 'Staff' not found.

bobbybouwmann's avatar

Here is a little example:

Movie.php

class Movie extends Model {
    
    /**
     * Get all genres connected to a movie
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
     */
    public function genres()
    {
        return $this->morphMany('App\Genre', 'genreable');
    }

}

Genre.php

class Genre extends Model {

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

}

Please or to participate in this conversation.