View Presenter Classes for Eloquent Models
Published on by Paul Redmond
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:
use App\Models\Presenters\UserPresenter;use TheHiveTeam\Presentable\HasPresentable; class User extends Model{ use HasPresentable; 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:
namespace App\Models\Presenters; use TheHiveTeam\Presentable\Presenter; class UserPresenter extends Presenter{ public function name() { return ucwords($this->model->name); }}
Using the User
model as an example, you can now access presenter methods in the view:
$user->present()->name;
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.