Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Joseph Silber:
How to rid your database of PHP class names in Eloquent's Polymorphic tables
Jul 05, 2018 @ 14:53:27

In a new post to his site site Joseph Silber shows you how, when using Eloquent in a Laravel application, to decouple your application from your database by removing hard-coded class names on polymorphic relationships.

Polymorphic relations let you set up a relationship between many different model types, without the need for extra tables. This works by storing the "morphable type" (explained below) in the database, in addition to the morphable type's ID.

By default, the morphable type stored in the database is the model's full class name. While this works, it tightly couples your database to your PHP application. Let's look at how we can instruct Eloquent to use more generic values for these morphable types.

He starts in with a "short refresher" on polymorphic relationships and what Eloquent models look like for a simple customer-to-address relationship. He then talks some about the "morph" type and how Eloquent stores the name of the relating model directly in the record (like AppCustomer or AppWarehouse). He shows how to customize the morph type to map the types to values in a morphMap setting to remove the need for those hard-coded class names. He wraps up the post answering the question many ask: "why doesn't Eloquent do this automatically?"

tagged: eloquent database polymorphic table relationship mapping tutorial

Link: https://josephsilber.com/posts/2018/07/02/eloquent-polymorphic-relations-morph-map


Trending Topics: