Ardian Riftha Dhuha
Ardian Riftha Dhuha

Reputation: 11

Laravel 5 best approach to retrieve all polymorphic models

i am new with laravel and I have a question while using polymorphic relationship.

Here is my simplified table structure :

polls
  id - integer
  name - string
  created_at - timestamp
  updated_at - timestamp

posts
  id - integer
  title - string
  created_at - timestamp
  updated_at - timestamp

contents
  id - integer
  contentable_id - integer
  contentable_type - string
  created_at - timestamp
  updated_at - timestamp

Ps. polls and posts table have same column but some of it use different naming

My Poll model :

class Poll extends Model
{
    /**
     * Get all of the post's contents.
     */
    public function contents()
    {
        return $this->morphMany('App\Models\Content', 'contentable');
    }
}

My Post model :

class Post extends Model
{
    /**
     * Get all of the post's contents.
     */
    public function contents()
    {
        return $this->morphMany('App\Models\Content', 'contentable');
    }
}

My Content model :

class Content extends Model
{
    /**
     * Get all of the owning contentable models.
     */
    public function contentable()
    {
        return $this->morphTo();
    }
}

I want to retrieve all models from Content including Post and Poll, then create the list of it using foreach loop like this

$contents = Content::with('contentable')->get();

foreach($contents as $content)
{
    $contentable = $content->contentable;

    //if its a poll then show title, created_at, and updated_at

    //or

    //if it's a post then show name, created_at, and updated_at 
}

My question is,

  1. What is the best approach to show the different column, like title column OR name column at once?
  2. Can i use column alias in this case? so i just call the alias

Upvotes: 1

Views: 3226

Answers (1)

J. Doe
J. Doe

Reputation: 1732

Add to your Content model

public function post()
{
   return $this->hasOne(Post::class, 'id', 'contentable_id')
       ->where('contentable_type', Post::class);
}
public function poll()
{
   return $this->hasOne(Poll::class, 'id', 'contentable_id')
        ->where('contentable_type', Poll::class);
}

And now you can this:

$contents = Content::with('contentable')->get();

foreach($contents as $content)
{

      $name = $content->post->name;
      //or $title = $content->poll->title
}

But, i dont understand why you need this relation, you can create one table(posts/polls) with this structure

id|name|category(post/poll)|created_at|updated_at

Upvotes: 1

Related Questions