Skip to content
Advertisement

Explain Eloquent morphMany parameters

I am new to laravel, can someone explain to me the parameters of morphMany:

$this->morphMany(Photo::class, 'imageable');

Advertisement

Answer

The MorphMany relationship has the following function signature:

public function morphMany($related, $name, $type = null, $id = null, $localKey = null)
{
    //
}

Where:

  • $related (required): refers to the related model. e.g: User::class.
  • $name (required): the name of the polymorphic relation, like commentable.
  • $type (optional): customize the {relation}_type field to look up when doing a query.
  • $id (optional): customize the {relation}_id field to look up when doing a query.
  • $localKey (optional): customize the local key (by default id) to search when doing a query.

So -using the example shown in the Laravel documentation– if you want to use a different table structure for the comments table from this:

posts
    id - integer
    title - string
    body - text

videos
    id - integer
    title - string
    url - string

comments
    id - integer
    body - text
    commentable_id - integer
    commentable_type - string

to this:

posts
    id - integer
    title - string
    body - text

videos
    id - integer
    title - string
    url - string

comments
    id - integer
    body - text
    foo - integer // the index to look
    bar - string // the type to match

You’d need to define your relationships like this:

Post.php

public function comments()
{
    return $this->morphMany(Comment::class, 'commentable', 'foo', 'bar');
}

Video.php

public function comments()
{
    return $this->morphMany(Comment::class, 'commentable', 'foo', 'bar');
}

Comment.php

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

Check this other answer.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement