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
}
You could use the Laravel Auto Present package for this. It will allow you to implement a presenter class on the model with specific methods to override the models normal data properties. However, I don't believe this will format the data on the way in to the model (if that's what you mean by inverse).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.