Customizing columns in the selection in Morphic Relationships in Laravel
Using a morphic relationship, I'm going to show you how you can create different columns. It's that simple. Although it sounds more complex than it seems, it's exactly what you can see here.
I'm building a shopping cart. Note that, for my online store, the products can be tutorials or books. What's the dilemma?
For example, for courses, I have some that include the option to decide if you want:
- Source code per class.
- Exclusive classes.
This corresponds to the panel we have here, and since it influences the price, I definitely need to pass that information to the shopping cart.
This pair of columns is not defined in the book template.
In the case of the book:
Only the complete purchase is allowed, with no additional options.
Otherwise, the other columns are exactly the same as the ones I referenced below.
The syntax is simple:
class ShoppingCart extends Model
{
***
public function itemable()
{
return $this->morphTo()->constrain([
Tutorial::class => function ($query) {
$query->select('id', 'title', 'url_clean', 'price', 'price_offers', 'exclusive_extra', 'price_code_extra');
},
Book::class => function ($query) {
$query->select('id', 'title', 'url_clean', 'price', 'price_offers'); // , NULL as price_exclusive_extra
},
]);
}
- In the method that indicates that it's a morphic relationship, we create a constraint.
- We indicate each of the relationships we have.
- We define the columns that must exist in each case.
In the book, the definition is simpler, as it doesn't require additional columns.
In the course, these additional columns do need to be defined.
This prevents the relationship from failing to search for nonexistent columns, as would happen if it were defined generically.
I agree to receive announcements of interest about this Blog.
I'll show you the configuration so you can customize the columns in a morphic relationship.