View Presenter Classes for Eloquent Models


August 19th, 2021

View Presenter Classes for Eloquent Models

The Laravel Presentable package by Jonathan Zarate is a package to create presenter classes for Eloquent models. A presenter class allows you to separate display concerns from model data in a dedicated class.

Here's an example from the README:

1use App\Models\Presenters\UserPresenter;
2use TheHiveTeam\Presentable\HasPresentable;
4class User extends Model
6 use HasPresentable;
8 protected $presenter = UserPresenter::class;

Eloquent models with a presenter class use the HasPresentable trait and a $presenter property that defines the presenter class.

Here's an example of what a presenter class will look like:

1namespace App\Models\Presenters;
3use TheHiveTeam\Presentable\Presenter;
5class UserPresenter extends Presenter
7 public function name()
8 {
9 return ucwords($this->model->name);
10 }

Using the User model as an example, you can now access presenter methods in the view:


This approach might be overkill depending on the goals of your application; however, if you find that separating view display logic into a dedicated presenter class makes sense, this package could be an excellent fit.

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.