Skip to content
Advertisement

Explain Eloquent morphMany parameters

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

JavaScript

Advertisement

Answer

The MorphMany relationship has the following function signature:

JavaScript

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:

JavaScript

to this:

JavaScript

You’d need to define your relationships like this:

Post.php

JavaScript

Video.php

JavaScript

Comment.php

JavaScript

Check this other answer.

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