DEV Community

Cover image for Laravel Presentable for Eloquent Models
Jonathan Zarate
Jonathan Zarate

Posted on

Laravel Presentable for Eloquent Models

Hey there!

Today was release of Laravel Presentable Package to 0.0.2 versión for support Laravel Framework v9.

This package allow create presenter classes for Eloquent models. A presenter class allows you to separate displays concerns from model data in a specific class.

Installation



composer require datacreativa/laravel-presentable


Enter fullscreen mode Exit fullscreen mode

For example add the trait HasPresentable to User Model.




use App\Models\Presenters\UserPresenter;
use TheHiveTeam\Presentable\HasPresentable;

class User extends Model
{
    use HasPresentable;

    protected $presenter = UserPresenter::class;
}



Enter fullscreen mode Exit fullscreen mode

$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);
    }
}


Enter fullscreen mode Exit fullscreen mode

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



$user->present()->name;


Enter fullscreen mode Exit fullscreen mode

If you find that separating view display logic into a dedicated presenter class makes sense, this package could be an excellent fit.

For more info, here the repository
https://github.com/datacreativa/laravel-presentable

Regards,
Jonathan

Top comments (0)