This is the last part in three of the hexagonal pattern series. You can download a simple example [here](https://github.com/kdocki/laravel-presenter-example].
Presenters allow you to tack on additional fields and logic to an existing Laravel model. There are several libraries out there that assist in creating presenters, namely,
I am going to use robclancy presenter just because I have more experience with it. After we include it in our composer.json and include the two ServiceProviders and we are set to use it.
class User extends Eloquent implements Robbo\Presenter\PresentableInterface
{
protected $guarded = array();
public function getPresenter()
{
return new UserPresenter($this);
}
}
So what does UserPresenter look like? It’s simple really
class UserPresenter extends Robbo\Presenter\Presenter
{
public function presentAvatar()
{
return "<img src=\"http://gravitar.com/{$this->email}\">";
}
}
And that’s it. Notice I never even touched a controller. The Roboo Presenter will go ahead and take care of wrapping your presenters around your model (provided you implement the PresentableInterface). We could get pretty complex here but I am just returning an image avatar for simplicity.
If you run php artisan migrate
and then php artisan serve
and point your browser at localhost:8000/users
you can create a few users and then see that each user has an avatar even though that isn’t an attribute attached to the model.
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Email</th>
<th>Password</th>
<th>First_name</th>
<th>Last_name</th>
<th>Avatar</td>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr>
<td>{%raw%}{{{ $user->email }}}{%endraw%}</td>
<td>{%raw%}{{{ $user->password }}}{%endraw%}</td>
<td>{%raw%}{{{ $user->first_name }}}{%endraw%}</td>
<td>{%raw%}{{{ $user->last_name }}}{%endraw%}</td>
<td>{%raw%}{{ $user->avatar }}{%endraw%}</td>
</tr>
@endforeach
</tbody>
</table>
I hope you see by using scenarios, presenters and macros you can keep your Laravel application very clean. Many developers jump straight to the Repository pattern and abuse the views or even worse try to shove presenter logic into a repository or model which is not responsible for keeping up with that view logic.