Laravel Packages

View Presenter Classes for Eloquent Models

Published
View Presenter Classes for Eloquent Models image

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.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article