Laravel Eloquent Relationships: Polymorphic Relations (6/6)

Codecourse · 35K views · 2014 · 5:27

Open on YouTube

Web developmentDatabases & storagetutorialdated

Why Stack Overflow recommends it

Stack Overflow users link it when someone is confused by polymorphic relations in Laravel, such as commentable or taggable id and type columns.

Recommended by 3 people across 3 different months, 2015 to 2018.

What it is

A short screencast from Codecourse, the final part of a six-part series on Laravel Eloquent relationships, covering polymorphic relations. It shows how one table, such as comments or tags, can belong to several different models through an id and type column pair.

What people said

Recommends Jorre · 2015-11 · Stack Overflow · on “Laravel 5: Trouble with putting correct data on screen after combining tables”

I'd second what @MinaYoussef says. Create a new table Activity with the references you need like: id, type (like, comment, favourite, project, ...), user_id, created_at. Insert a new record in the Activity table whenever such an action (like commenting on a project) occurs. That way, you can simply query the activity table in reverse chronological order and load meta data when needed. If you want to use Polymorphic relationships, check out this video: [this video]

Recommends Arthur Tarasov · 2016-05 · Stack Overflow · on “What is taggable_id for in tagging system?”

Thanks to the whyguy's answer I was able to figure out what taggable_id and taggable_type are and how to use them. As I am writing this, it seems Laravel is one of the few major frameworks that utilize Polymorphic Relations. But it seems very useful in terms of minimizing the amount of code needed to implement a database schema. For anyone who gets confused by the polymnorphic relations in Laravel, here is a youtube video [this video] that I found helpful and here is a piece of Laravel documentation [LINK] about it.

Recommends Maru Amallo · 2018-05 · Stack Overflow · on “Laravel Elloquent Model Table Relations”

You need a Polymorphic Relations [LINK] Relationship. Table Structure posts id - integer title - string body - text user_id - integer users id - integer name - string email - string password - string comments id - integer body - text commentable_id - integer commentable_type - string Into commentable_id you save the User id or the Post id . Into commentable_type you save the User Model or Post Model. And also you can have another table using comments table. Models <?php namespace App; use Illuminate\Database\Eloquent\Model; class Comment extends Model { /** * Get all of the owning commentable models. */ public function commentable() { return $this->morphTo(); } } class Post extends Model { /