Home » Php » php – What is the rule to create a polymorphic field name in Laravel?

php – What is the rule to create a polymorphic field name in Laravel?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m not new using Laravel but it’s first time that I need/want to use polymorphic relations.
I saw a example at Laravel.com and it says that I should use ‘imageable_id’ to a table called ‘images’, in another example I saw ‘commentable_id’ to table ‘comments’.

Is there a rule to create names?

For example: I want to create a table ‘category’ that will be used for ‘posts’ and ‘settings’. In this case, should I use ‘categoryable_id’ as name?

How to&Answers:

There is no rule, except a default convention. By default, you define the prefix and Laravel will set the _id and _type suffixes. The field is determined by what you define in the relationship:

For example, on either Posts or Settings:

public function category()
{
    return $this->morphMany('App\Category', 'categoryable');
}

With this, your model will search the table Category for categoryable_id and categoryable_type. categoryable_id by default will match your model id and categoryable_type will match your model’s FQCN (e.g. ‘App\Post’).

If you wish to change how Laravel sets the polymorphic column names, you can set those with the 3rd and 4th parameters of the same method, e.g.:

public function category()
{
    return $this->morphMany('App\Category', 'categoryable', 'model_type', 'model_id');
}

So there isn’t really a rule. You are free to define it as you wish, or utilize the default convention.

Source: http://laravel.com/docs/5.1/eloquent-relationships#many-to-many-polymorphic-relations