I'm just wondering how to go about implementing the Presenter pattern for attributes inside of a pivot table? For example, consider this code (it's just an example and is not a replication of my actual code):
@foreach($users->comments as $comment)
<h1>{{ $comment->title }}</h1> // calls 'title()' in CommentPresenter
<p>{{ $comment->body }}</p> // calls 'body()' in CommentPresenter...
<p>{{ is_null($comment->pivot->deleted_at) ? '' : '[REMOVED]' :}} // Where can I put this???
@endforeach
Where can I put that final attributes presenting method? Bearing in mind I also want to be able to use the inverse of this relation.
Any help greatly appreciated
Thanks!
You can override newPivot
in your models and then use your own Pivot
model. It will be treated mostly like a "normal" Eloquent model so the auto presenter package should work.
public function newPivot(Model $parent, array $attributes, $table, $exists)
{
if($parent instanceof User){
return new CommentUserPivot($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
public function newPivot(Model $parent, array $attributes, $table, $exists)
{
if($parent instanceof Comment){
return new CommentUserPivot($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
class CommentUserPivot extends \Illuminate\Database\Eloquent\Relations\Pivot {
// presenter stuff
}