Search code examples
laraveleloquentpolymorphic-associations

Get morphFrom on laravel polymorphic relation


I am using laravel polymorphic relationship

My Comment.php class

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $fillable = ['body', 'commentable_id', 'commentable_type'];

    /**
     * Get the owning commentable model.
     */
    public function commentable()
    {
        return $this->morphTo();
    }    

    // public function commentFrom()
    // {
    //   return where it commented from.
    // }
}

What I want: I want all comment with where it commented (post/video) from.


Solution

  • Just use with('commentable') to all the comments and its post or video:

    Comment::with('commentable')->get()