movepixels's avatar

Polymorphic View Assistance

I am building a Reviewable function simply when user add / edit certain parts of their account some of the sections of the account are "reviewable" by moderators. So upload new pictures they are reviewable, new post, same idea.

So I have my reviewables table saving as it should for these actions as needed, I can thru testing and logging see the morphed relationship data but since the records all have different columns how do you return a view / blade to display on a page to properly review. Media has a url basically i need to view the uploaded image and approve or reject it, Post has a title, category_id, description, and so on for the different reviewable types. Is it like make a partial for each and in a forech based on the model render a partial for that specific reviewable item?

How would / do you approach it?

Thanks,

Dave

0 likes
2 replies
jbloomstrom's avatar
Level 50

I think you're on to a good approach, dynamically include a partial specific to the reviewable_type. You could even add a trait to each reviewable model to simplify getting the partial name.

// trait added to Post, Comment, Picture etc.
use Illuminate\Support\Str;

trait CanGetReviewableTypePartialName {
  
  function getPartialNameAttribute() {
    // insert your own naming convention
   
    return "partials._" . Str::snake( class_basename( $this->reviewable ) );
    // App\Post becomes partials._post
    // App\PostPicture becomes partials._post_picture
  }
}


// your blade template

@foreach($rows as $row)
@include($row->partial_name, ['reviewable' => $row->reviewable])
@endforeach

movepixels's avatar

Thanks, I was thinking of adding a you suggested so each Model would be assigned a partial so use that as your snip shows to provide what partial to use based on the reviewable_type without having to really do much extra.

Please or to participate in this conversation.