Search code examples
phpdesign-patternslaraveleloquentpresenter

Using a presenter on attributes in a pivot table in Laravel


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!


Solution

  • 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.

    Comment model

    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);
    }
    

    User model

    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);
    }
    

    CommentUserPivot model

    class CommentUserPivot extends \Illuminate\Database\Eloquent\Relations\Pivot {
        // presenter stuff
    }