0

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!

keonovic
  • 47
  • 4

2 Answers2

1

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
}
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • I can't seem to get this working. I am using a ->belongsToMany relationship on both tables, I don't know if that makes any difference? It just seems like it is never calling 'newPivot' – keonovic Jan 16 '15 at 10:17
  • Have you added the `newPivot` to both models? When using `$user->comments` `newPivot` will be called in the `Comment` model – lukasgeiter Jan 16 '15 at 10:27
  • Never mind it is working correctly, thanks! My issue is though that the auto presenter package I'm using doesn't seem to be decorating the Pivot – keonovic Jan 16 '15 at 11:07
  • Okay. Unfortunately I can't help you with that. Never used the package. Good luck though! – lukasgeiter Jan 16 '15 at 12:01
0

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

https://github.com/ShawnMcCool/laravel-auto-presenter

  • I'm using this exact package, I'm wondering how to present 'pivot' attributes though rather than just the ones on the Model I'm presenting (eg. the attributes that would be on the `users_comments` table in my example, as oppose to `users` table) – keonovic Jan 15 '15 at 15:04