Illuminate\Database\Eloquent\Model::morphTo PHP Method

morphTo() public method

Define a polymorphic, inverse one-to-one or many relationship.
public morphTo ( string $name = null, string $type = null, string $id = null ) : Illuminate\Database\Eloquent\Relations\MorphTo
$name string
$type string
$id string
return Illuminate\Database\Eloquent\Relations\MorphTo
    public function morphTo($name = null, $type = null, $id = null)
    {
        // If no name is provided, we will use the backtrace to get the function name
        // since that is most likely the name of the polymorphic interface. We can
        // use that to get both the class and foreign key that will be utilized.
        if (is_null($name)) {
            list($current, $caller) = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
            $name = $caller['function'];
        }
        list($type, $id) = $this->getMorphs(Str::snake($name), $type, $id);
        // If the type value is null it is probably safe to assume we're eager loading
        // the relationship. In this case we'll just pass in a dummy query where we
        // need to remove any eager loads that may already be defined on a model.
        if (empty($class = $this->{$type})) {
            return new MorphTo($this->newQuery()->setEagerLoads([]), $this, $id, null, $type, $name);
        } else {
            $class = $this->getActualClassNameForMorph($class);
            $instance = new $class();
            if (!$instance->getConnectionName()) {
                $instance->setConnection($this->connection);
            }
            return new MorphTo($instance->newQuery(), $this, $id, $instance->getKeyName(), $type, $name);
        }
    }

Usage Example

Example #1
0
 public function morphTo($name = null, $type = null, $id = null)
 {
     if (is_null($name)) {
         $backtrace = debug_backtrace(false, 4);
         $caller = $backtrace[3];
         $name = snake_case($caller['function']);
     }
     return parent::morphTo($name, $type, $id);
 }
All Usage Examples Of Illuminate\Database\Eloquent\Model::morphTo
Model